📜  如何在Python中读取文件

📅  最后修改于: 2022-05-13 01:55:23.213000             🧑  作者: Mango

如何在Python中读取文件

Python提供了用于创建、写入和读取文件的内置函数。在Python中可以处理两种类型的文件,普通文本文件和二进制文件(用二进制语言编写,0 和 1)。

  • 文本文件:在这种类型的文件中,每一行文本都以一个叫做 EOL(End of Line)的特殊字符结束,在Python中默认是字符('\n')。
  • 二进制文件:在这种类型的文件中,行没有结束符,数据在转换成机器可以理解的二进制语言后存储。

注意:要了解有关文件处理的更多信息,请单击此处。

访问方式

访问模式控制打开文件中可能的操作类型。它指的是文件打开后将如何使用。这些模式还定义了文件句柄在文件中的位置。文件句柄就像一个游标,它定义了必须从哪里读取或写入文件中的数据。读取文件的不同访问模式是 -

  1. 只读 ('r') :打开文本文件进行阅读。句柄位于文件的开头。如果文件不存在,则引发 I/O 错误。这也是打开文件的默认模式。
  2. 读写('r+'):打开文件进行读写。句柄位于文件的开头。如果文件不存在,则引发 I/O 错误。
  3. Append and Read ('a+') :打开文件进行读写。如果文件不存在,则创建该文件。句柄位于文件的末尾。正在写入的数据将插入到末尾,在现有数据之后。

注意:要了解有关访问模式的更多信息,请单击此处。

打开文件

它是使用open()函数完成的。此函数不需要导入任何模块。

句法:

File_object = open(r"File_Name", "Access_Mode")

该文件应与Python程序文件存在于同一目录中,否则文件的完整地址应写在文件名的位置。

注意: r放在文件名之前,以防止文件名字符串中的字符被视为特殊字符。例如,如果文件地址中有 \temp,则 \t 被视为制表字符,并且由于地址无效而引发错误。 r 使字符串原始,也就是说,它告诉字符串没有任何特殊字符。如果文件在同一目录中并且没有放置地址,则可以忽略 r。

# Open function to open the file "MyFile1.txt"  
# (same directory) in read mode and 
file1 = open("MyFile.txt", "r") 
    
# store its reference in the variable file1  
# and "MyFile2.txt" in D:\Text in file2 
file2 = open(r"D:\Text\MyFile2.txt", "r+") 

这里,file1 被创建为 MyFile1 的对象,file2 被创建为 MyFile2 的对象。

关闭文件

close()函数关闭文件并释放该文件获取的内存空间。它在不再需要文件或要以不同的文件模式打开时使用。

句法:

File_object.close()
# Opening and Closing a file "MyFile.txt" 
# for object name file1. 
file1 = open("MyFile.txt", "r") 
file1.close() 

从文件中读取

有三种方法可以从文本文件中读取数据。

  • read() :以字符串的形式返回读取的字节。读取 n 个字节,如果没有指定 n,则读取整个文件。
    File_object.read([n])
    
  • readline() :读取文件的一行并以字符串的形式返回。对于指定的n,最多读取n个字节。但是,不会读取超过一行,即使 n 超过了行的长度。
    File_object.readline([n])
    
  • readlines() :读取所有行并将它们作为每行返回一个列表中的字符串元素。
    File_object.readlines()
    

注意: '\n'被视为两个字节的特殊字符。

例子:

# Program to show various ways to 
# read data from a file. 
  
# Creating a file
file1 = open("myfile.txt", "w")
L = ["This is Delhi \n", "This is Paris \n", "This is London \n"]
  
# Writing data to a file
file1.write("Hello \n") 
file1.writelines(L)
file1.close()  # to change file access modes
  
file1 = open("myfile.txt", "r+")
  
print("Output of Read function is ")
print(file1.read())
print()
  
# seek(n) takes the file handle to the nth
# bite from the beginning. 
file1.seek(0)
  
print("Output of Readline function is ")
print(file1.readline())
print()
  
file1.seek(0)
  
# To show difference between read and readline 
print("Output of Read(9) function is ")
print(file1.read(9))
print()
  
file1.seek(0)
  
print("Output of Readline(9) function is ")
print(file1.readline(9))
print()
  
file1.seek(0)
  
# readlines function 
print("Output of Readlines function is ")
print(file1.readlines())
print()
file1.close() 

输出:

Output of Read function is
Hello
This is Delhi
This is Paris
This is London


Output of Readline function is
Hello


Output of Read(9) function is
Hello
Th

Output of Readline(9) function is
Hello


Output of Readlines function is
['Hello \n', 'This is Delhi \n', 'This is Paris \n', 'This is London \n']

带声明

Python中的with语句用于异常处理,以使代码更简洁、更具可读性。它简化了文件流等公共资源的管理。与上述实现不同,使用 with 语句时无需调用file.close()with语句本身确保正确获取和释放资源。

句法:

with open filename as file:
# Program to show various ways to
# read data from a file.
  
L = ["This is Delhi \n", "This is Paris \n", "This is London \n"]
  
# Creating a file
with open("myfile.txt", "w") as file1:
    # Writing data to a file
    file1.write("Hello \n")
    file1.writelines(L)
    file1.close()  # to change file access modes
  
with open("myfile.txt", "r+") as file1:
    # Reading form a file
    print(file1.read())

输出:

Hello
This is Delhi
This is Paris
This is London

注意:要了解有关 with 声明的更多信息,请单击此处。