Python文件的读取写入操作

一、打开文件、关闭文件操作

想要读取文件或是写入文件,第一步便是打开文件,最后一步便是关闭文件。这里介绍两种打开(关闭)文件的方式:

1、open()方法
f=open(file_name[,access_mode][,buffering])
f=close()

其中,file_name代表文件名,若文件在同一路径下直接输入文件名+后缀,不在同一路径下则写出具体路径;access_mode代表打开文件的方式,默认为r只读模式;buffering代表寄存。

文件的打开方式有如下几种:

r:只读模式

w:用新内容覆盖原文件内容,当文件不存在时,该方式会自动创建文件

a:在原文件中继续写入数据

r+可读可写

w+:打开一个文件用于读写。如果该文件已存在则将其覆盖。如果该文件不存在,创建新文件。

a+:打开一个文件用于读写。如果该文件已存在,文件指针将会放在文件的结尾。文件打开时会是追加模式。如果该文件不存在,创建新文件用于读写。

rb wb ab 读写二进制

若想向文本中写入数据,更改代码如下:

f=open("seed.txt","w")
f=close()

需要注意的是,open()方法必须和close()一起使用,打开文件使用完毕后一定要关闭文件。

2、with open() as方法
with open("seed.txt","r",encoding="utf-8"):    #encoding为编码格式,此处为utf8格式
    ......   #文件操作

该方法会自动关闭文件,以防止出现操作复杂,编写时间久导致遗落文件关闭步骤的情况,个人更推荐在使用文本时使用该方法操作。

二、读取文件操作

1、read()
  读取文件所有内容,以字符串形式返回。
with open('seed.txt','r',encoding='utf-8') as f:
    print(f.read())

2、readline()
  读取文件中的一行,读取后,文件指针自动移至下一行开头,以字符串形式返回。
with open('seed.txt','r',encoding='utf-8') as f:
    print(f.readline())

 
3、readlines()
  读取文件的每一行,以列表形式返回。
  这个函数是以内部循环调用readline()方法实现的。
with open('seed.txt','r',encoding='utf-8') as f:
    for i in f.readlines():
        print(i,end='')
    print()
    print(type(f.readlines()))

三、常规写入文件操作

1、write(str)

  将str写入文件中,默认不换行,换行需手动添加‘ ’。

  添加换行符‘ ’:

s='abcd
efgh'
with open('seed.txt','w+',encoding='utf-8') as f:
    f.write(s)

with open('seed.txt','r',encoding='utf-8') as f:
    for i in f.readlines():
        print(i,end='')
    print()

  不添加换行符:

s='abcdefgh'
with open('seed.txt','w+',encoding='utf-8') as f:
    f.write(s)

with open('seed.txt','r',encoding='utf-8') as f:
    for i in f.readlines():
        print(i,end='')
    print()

2、writelines(seq)

  将seq(序列)中的数据多行一次写入文件中,不会自动换行,需手动添加换行符。

  手动添加换行符‘ ’:

s=['abc
def']
with open('seed.txt','w+',encoding='utf-8') as f:
    f.writelines(s)

with open('seed.txt','r',encoding='utf-8') as f:
    for i in f.readlines():
        print(i,end='')
    print()

   不添加换行符:

s=['abcdef','qwe']
with open('seed.txt','w+',encoding='utf-8') as f:
    f.writelines(s)

with open('seed.txt','r',encoding='utf-8') as f:
    for i in f.readlines():
        print(i,end='')
    print()

 四、指定读取写入文件操作

1、seek(size)

  文件指针指向size字节处,并从此处读取或写入数据。

  写入数据:

s='abcdefgh'
b='123'
with open('seed.txt','w+',encoding='utf-8') as f:
    f.write(s)
    f.seek(3)
    f.write(b)

with open('seed.txt','r',encoding='utf-8') as f:
    print(f.readline())
    print()

   

  读取数据(文件接上一个例子):

with open('seed.txt','r',encoding='utf-8') as f:
    f.seek(2)
    print(f.readline())
    f.seek(0)
    print(f.readline())
    f.seek(6)
    print(f.readline())

原文地址:https://www.cnblogs.com/zhangmingfeng/p/11879287.html