使用python打开和修改文件--open功能

Posted 文仙草

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用python打开和修改文件--open功能相关的知识,希望对你有一定的参考价值。

一、基本格式和模式

open: 将导入的文件生成文件对象(file object) 并返回该文件对象。 python自带,不需要import任何library。

  • 格式:file = open(filepath,mode) 。mode可以为’r’, ‘w’, ‘a’。

可使用的模式:r(只读),w(创建新文件并修改),a(在已存在的文件上进行修改)

  • 实例1:file = open(‘data.xlsx’, ‘r’), 只读模式打开名为data的文件,如该文件不存在则报错。
  • 实例2:file = open(‘data.xlsx’, ‘w’),创建一个名为data的新文件,可对该文件的内容进行修改。如果已经存在同名文件,则覆盖该文件。
  • 实例3:file = open(‘data.xlsx’, ‘a’),创建一个名为data的新文件,可对该文件的内容进行修改。如果已经存在同名文件,则打开该同名文件进行修改。

二、file对象可使用的方法

  • file.name:获取文件名
  • file.mode:获取文件的打开模式
  • file.close: 关闭文件
  • file.closed: 判断文件是否已经关闭,返回True or False
(一)在只读模式’r’下可使用的
  • file.read(n):返回文件对象前n个字符(注:换行符也算一个字符)。如果不写n,则返回文件对象中的全部内容。需注意,如之前运行了.read(n)或者.readline(n),则文件开始的位置是上次读取结束的后一位。
  • file.readline(n): 返回文件对象里的第一行的前n个字符;如果不写n,则返回文件对象第一行全部内容;如果n大于第一行字符个数,则返回第一行全部内容。需注意,第一次使用readline时,第一行默认为第一个换行符之前的内容,如果连续使用readline,则会依次往后推,详见示例。
  • file.readlines(): 获取文件对象里的所有内容,并返回一个存储了文件对象内容的列表,默认每个换行符对应列表里的一个元素。

.read(n) vs .readline(n):与.read()不同,readline()只能读取一行的内容。如果n大于该行字符个数,.read(n)会继续读取下一行,.readline()不会继续读下一行。

(二)在修改模式‘w’和’a’下可使用的
  • file.write()
  • 但是不能使用.read(), .readline(), .readlines()等只读模式下的方法。

三、实际操作

特别注意!要记得关闭被打开的文件。

一般使用with open as filename: 格式来操作文件。程序会执行with下面的代码块,执行完代码块之后会自动关闭文件,无需写file.close().

(一)读写模式下(w)
lines = ['hello,\\n', 'my name is becky.']
#创建一个名为example的新文本文件
with open('data/example.txt', 'w') as file1:
    #每次写入一行数据(\\n为换行符)
    file1.write('This is a new exercise.\\n')
    #或者利用循环写入多行数据
    for line in lines:
        file1.write(line)
#【结果】
#在该程序所在文件夹创建了一个新文件example.txt,该文件里的内容是:
#This is a new exercise
#hello, 
#my name is becky. 
(二)读写模式下(a)
with open('data/example.txt', 'a') as file1:
    file1.write('This is a new exercise.\\n')
    file1.write('This is the last sentence.\\n')
#【结果】
#在该程序所在文件夹的文件example.txt里的内容应变为:
#This is a new exercise    
#hello, 
#my name is becky. This is a new exercise.
#This is the last sentence.
(三)只读模式下(r)
with open('data/example.txt', 'r') as file1:
    print(file1.name)  
    print(file1.mode)
    content = file1.read()
    content_1 = file1.readlines()
print(content)
print(f'this is content_1: {content_1}')
#【结果】
#example.txt
#r
#This is a new exercise
#hello, 
#my name is becky. This is a new exercise.
#This is the last sentence.   
#this is content_1: ['This is a new exercise\\n', 'hello,\\n','my name is becky. This is a new exercise.\\n', 'This is the last sentence.\\n']
(四)只读模式下( r ),不能修改文件内容
with open('data/example.txt', 'r') as file1:
    content = file1.readline()
    print(content)
    file1.write('try it')
#【结果】
#This is a new exercise
#UnsupportedOperation .......(省略XX字的错误信息)......
#UnsupportedOperation: not writable
(五)获取文件中的部分内容
with open('data/example.txt', 'r') as file1:
    print(file1.read(4))
    print(file1.read(4))
    print('this is readline:', file1.readline(13))
    print('this is readline with limit:', file1.readline(5))
#【结果】
#This
# is  (注意此处is前后各有一个空格)
#this is readline: a new exercis (注意,从上次读取的文件位置后一位开始)
#this is readline with limit: e.
#       (此处是换行符引起的空行,而且不会进入到下一行)
(六)连续使用file.readline(),获取的行内容会依次后推
with open('data/example.txt', 'r') as file1:
    print(file1.readline())
    print(file1.readline())
    print(file1.readline())
#【结果】
#This is a new exercise.
#(此处为空行)
#hello,
#(此处为空行)
#my name is becky.This is a new exercise.
(七)将文件A中的内容复制黏贴到文件B中

示例:将上述文件example.txt中的内容复制到新的文件test.txt中。example.txt文件在data子文件夹中,test.txt文件在test子文件夹中(注:test子文件夹需存在)。

with open('data/example.txt', 'r') as readfile:
    with open('test/test.txt', 'w') as writefile:
        for line in readfile:
            writefile.write(line)
        print(writefile.closed) #测试writefile是否关闭
    print(writefile.closed) #测试writefile是否关闭

#【结果】
#(text子文件夹中出现test.txt文件,且文件内容与example.txt文件内容一致)
#False
#True           

四、其他模式

r+ : 可以读取(reading)和修改(writing)文件, 但文件对象不能truncate.
w+ : 可以读取(reading)和修改(writing)文件, 文件对象可以truncate.
a+ : 可以读取(reading)和增改(appending)文件. 如果文件不存在,则创建新文件.

  • a+模式示例1
with open('Example2.txt', 'a+') as testwritefile:
    testwritefile.write('This is a new line.\\n')
    print(testwritefile.read())
#【结果】
#(空行)

在a+模式下,打开文件后, 默认光标在文件结尾处, 所以新语句"This is new line." 添加在文件末尾.

同理, 由于添加完新的语句之后, 光标在结尾处, 而新语句的结尾是一个换行符, 所以此时调用read()方法, 读取的是光标所在位置, 即空行.

由此引深, read(), write()都是在文件对象某个特定的位置进行读取或写入, 可以将这个位置想象为光标所在的位置.

在 w / w+ 模式下打开文件, 类似于打开文件, 将光标移动到该文件的开头处,写入新文本并删除后面的所有内容。 而在 a/a+ 模式下打开 .txt文件类似于打开文件, 将光标移动到文件末尾, 然后添加新的文本片段。

因此, 知道“光标”在文件中的位置并能够控制"光标"移动非常有用, 一般用以下两个方法:

  • .tell() : 以字节为单位返回"光标"当前位置.
  • seek(offset,from) : 从 ‘from’ 所在位置, 向后移动 ‘offset’ 个字节位置。 from取值范围是0,1,2, 其中0代表"文件开头", 1代表"相对于当前位置", 2代表"文件末尾".

对a+模式示例1进行修改, 获取并移动"光标"位置,

with open('Example2.txt', 'a+') as testwritefile:
    print(f'Initial Location: {testwritefile.tell()}')
    
    data = testwritefile.read()
    if (not data):  #empty strings return false in python
        print('Read nothing') 
    else: 
        print(testwritefile.read())
            
    testwritefile.seek(0,0) # move 0 bytes from beginning.
    
    print(f'\\nNew Location : {testwritefile.tell()}')
    data = testwritefile.read()
    if (not data): 
        print('Read nothing') 
    else: 
        print(data)
    
    print("Location after read: {}".format(testwritefile.tell()) )

#【结果】
#Initial Location: 21
#Read nothing
#
#New Location : 0
#This is a new line.
#
#Location after read: 21

w+ 模式与 r+ 模式的异同: 两种模式都能读(read)和写(write)文件, 但在w+模式下打开文件将覆盖并删除原文件中所有已存在的数据.
a+ 模式与 r+ 模式的异同: 两中模式都适用于需要保留原文件数据的情况。当用r+模式时,可以使用 .truncate() 方法,a+method at the end of your data. This will reduce the file to your data and delete everything that follows.

  • 示例
with open('Example2.txt', 'r+') as testwritefile:
    data = testwritefile.readlines()
    testwritefile.seek(0,0) #write at beginning of file
   
    testwritefile.write("Line 1" + "\\n")
    testwritefile.write("Line 2" + "\\n")
    testwritefile.write("Line 3" + "\\n")
    testwritefile.write("finished\\n")
 
    testwritefile.truncate()
    testwritefile.seek(0,0)
    print(testwritefile.read())
    
#【结果】
#Line 1
#Line 2
#Line 3
#finished
# line D
#This is line E
#This is line E   

以上是关于使用python打开和修改文件--open功能的主要内容,如果未能解决你的问题,请参考以下文章

使用python打开和修改文件--open功能

第六章Python文件操作

Python之文件操作

python读写文件

python中用open保存文本到桌面

python 文件内容修改替换操作