1 open方法
open方法,Python 将以默认的只读模式打开文件。
读取文本文件时,Python将其中所有文本都解读为字符串。如果需要将起作为数来使用,可以用int()或float()将其转换成数。
建立记事本,存入py相同路径:
1.1 一次读取一行
编写代码 :file_object作为”pi_digits.txt“的对象返回。
with open('pi_digits.txt') as file_object:
#一次读取一行
for line in file_object:
print(line.rstrip())
执行结果(每次打印完会有空行,可以采用rstrip去除空行:
3.1415926535
8979323846
2643383279
1.2 一次全部读取
代码:
with open('pi_digits.txt') as file_object:
#一次全部读取txt中内容
contents=file_object.read()
print(contents.rstrip())#通过rstrip删除字符串末尾的空白
执行结果:
3.1415926535
8979323846
2643383279
1.3 在with外部使用文件中的内容
通过 readlines()从文件中读取每一行,并将其存储在一个列表lines中。
代码:
with open('pi_digits.txt') as file_object:
#读取各行,并以列表的形式存入lines中
lines=file_object.readlines()
pi_string=''
for line in lines:
print(line.rstrip())#打印每一行
pi_string+=line.strip()#圆周率
print(pi_string)#打印圆周率
print(len(pi_string))#圆周率的位数
执行结果:
3.1415926535
8979323846
2643383279
3.141592653589793238462643383279
32
2 写文件
Python 只能将字符串写入文本文件。要将数值数据存储到文本文件中,必须先使用函数
str()将其转换为字符串格式。
open方法: open(filename, 'w')
(1)’w'表示写入模式,如果写入的文件不存在,open()会自动创建它;
(2)以写入模式('w')打开文件时千万要小心,因为如果指定的文件已经存在,Python 将在返回文件对象前清空该文件的内容;
(3)第二个参数也可以是:读取模式('r')、写入模式('w')、附加模式('a')或读写模式('r+')
2.1 写入一个字符串
代码:
#将pi_string的字符写入文件file_write.txt
with open('file_write_new.txt','w') as file_object_w:
file_object_w.write(pi_string)
执行结果:
2.2 写入多行
使用空格、制表符和空行来设置输出到文件的格式。
代码:
with open('file_write_new.txt','w') as file_object_w:
file_object_w.write("first line\n")
file_object_w.write("second line\n")
执行结果:
2.3 在文件末尾写入内容
open第二个参数指定了实参'a',以附加模式打开文件,将写入文件的行添加到文件末尾。
代码:
with open('file_write_new.txt','w') as file_object_w:
file_object_w.write("first line\n")
file_object_w.write("second line\n")
with open('file_write_new.txt','a') as file_object_w:
file_object_w.write("third line\n")
file_object_w.write("fouth line\n")
执行结果: