在Python中,文件的读写操作是实用的编程任务之一。本文将详细介绍利用python读取、写入文件的基础方法。

读取文件

在Pyhton3中,读取文件前需先打开文件。可以利用Python的open()函数打开文件。

file1=open('/User/ikun/gege.txt','r') #填入文件的路径
file2=open('gege.txt','r') #需要让txt文件与程序在同一个目录中

程序中的标识符‘r’,表示只读

如果文件在路径中不存在,则会出现IOError异常。可以用try-except语句处理报错。

read()函数可以把文件中的内容先存储在存,而后输出为字符串read()函数会一次性读取整个文件,而readlines()可以逐行读取文件。

my_file=open('QRX.txt','r')
print(file.read())
print(file.readlines())

在读取文件后需要关闭文件,以减小内存占用。

my_file.close()

python中的with语句可以简化这个操作。with语句打开的文件会在程序末尾自动关闭。

Qin_ru_xin_path='/User/qin/calculus.txt'
with open(Qin_ru_xin_path,'r') as qinru:
    q=qinru.read()
    print(q)
#文件已被自动关闭

二进制文件

在读取图片,视频文件等二进制文件时时,需要标识符‘rb’

pic=open('art.jpg','rb')
print(pic.read)
#返回结果将会是十六进制字节

写入文件

与读取文件相似,写入文件可以使用‘w’‘wb’标识符。

f=open('/Users/hello/hi.txt', 'w')
f.write('Hello, world!')
f.close()

‘w’模式会让输入内容覆盖文件原有内容。如果想将内容追加在文件末尾,看使用‘a’(append)模式

Qin_ru_xin_path='/User/qin/calculus.txt'
with open(Qin_ru_xin_path,'a') as qinru:
    qinru.write('微积分')
#文件已被自动关闭
28 thoughts on “Python文件读写”
      1. I have been browsing online more than 2 hours today, yet
        I never found any interesting article like yours. It is pretty worth enough for me.
        Personally, if all webmasters and bloggers made good content as
        you did, the internet will be much more useful than ever before.

    1. Hello! I realize this is sort of off-topic however I had to ask.

      Does managing a well-established website like yours require
      a massive amount work? I’m brand new to operating a blog but I do write in my diary
      on a daily basis. I’d like to start a blog so I will be able
      to share my own experience and views online. Please let me
      know if you have any kind of suggestions or tips for new aspiring blog owners.
      Appreciate it!

    1. Great job on this insightful post. Your writing is captivating and your thoughts are clearly stated. Looking forward to more posts.

回复 Theodora 取消回复

您的邮箱地址不会被公开。 必填项已用 * 标注