📜  在Python中读取和写入文本文件

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

在Python中读取和写入文本文件

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

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

在本文中,我们将重点介绍在文本文件中打开、关闭、读取和写入数据。

文件访问模式

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

  1. 只读 ('r') :打开文本文件进行阅读。句柄位于文件的开头。如果文件不存在,则引发 I/O 错误。这也是打开文件的默认模式。
  2. 读写('r+'):打开文件进行读写。句柄位于文件的开头。如果文件不存在,则引发 I/O 错误。
  3. Write Only ('w') :打开文件进行写入。对于现有文件,数据将被截断并覆盖。句柄位于文件的开头。如果文件不存在,则创建文件。
  4. Write and Read ('w+') :打开文件进行读写。对于现有文件,数据将被截断并覆盖。句柄位于文件的开头。
  5. Append Only ('a') :打开文件进行写入。如果文件不存在,则创建该文件。句柄位于文件的末尾。正在写入的数据将插入到末尾,在现有数据之后。
  6. 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 append mode and
file1 = open("MyFile.txt","a")
  
# store its reference in the variable file1 
# and "MyFile2.txt" in D:\Text in file2
file2 = open(r"D:\Text\MyFile2.txt","w+")

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

关闭文件

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

File_object.close()

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

写入文件

有两种方法可以写入文件。

  1. write() :在文本文件的单行中插入字符串str1。
    File_object.write(str1)
  2. writelines() :对于字符串元素的列表,将每个字符串插入到文本文件中。用于一次插入多个字符串。
    File_object.writelines(L) for L = [str1, str2, str3] 

从文件中读取

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

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

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

# Program to show various ways to read and
# write data in a file.
file1 = open("myfile.txt","w")
L = ["This is Delhi \n","This is Paris \n","This is London \n"] 
  
# \n is placed to indicate EOL (End of Line)
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))
  
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 program to illustrate
# Append vs write mode
file1 = open("myfile.txt","w")
L = ["This is Delhi \n","This is Paris \n","This is London \n"] 
file1.writelines(L)
file1.close()
  
# Append-adds at last
file1 = open("myfile.txt","a")#append mode
file1.write("Today \n")
file1.close()
  
file1 = open("myfile.txt","r")
print("Output of Readlines after appending") 
print(file1.readlines())
print()
file1.close()
  
# Write-Overwrites
file1 = open("myfile.txt","w")#write mode
file1.write("Tomorrow \n")
file1.close()
  
file1 = open("myfile.txt","r")
print("Output of Readlines after writing") 
print(file1.readlines())
print()
file1.close()

输出:

Output of Readlines after appending
['This is Delhi \n', 'This is Paris \n', 'This is London \n', 'Today \n']

Output of Readlines after writing
['Tomorrow \n']


相关文章:
Python中的文件对象