Python 文件
1.读取整个文件
我们首先在存放代码的位置下新建一个名为data的txt文件,并在里面存放一些数据。
【实例】:
with open("D:\Code\Python\data.txt",encoding='UTF-8') as file_object:
contents = file_object.read()
print(contents)
【运行结果】:
123456789
987654321
hello world!
2.逐行读取
【实例】:
with open("D:\Code\Python\data.txt",encoding='UTF-8') as file_object:
for line in file_object:
print(line)
【运行结果】:
123456789
987654321
hello world!
3.将文件中各行内容存入列表
【实例】:
with open("D:\Code\Python\data.txt",encoding='UTF-8') as file_object:
lines = file_object.readlines()
for line in lines:
print(line.rstrip())
【运行结果】:
123456789
987654321
hello world!
4.写入文件
open()方法第二个参数为打开文件的模式:读取模式(r),写入模式(w),附加模式(a),读写模式(r+)。
如果要写入的文件不存在,python会自动创建它。如果文件存在,python会事先清空文件后再返回文件对象。
【实例】:
with open("D:\Code\Python\write.txt",'w') as file_object:
file_object.write("hello world!")
注意:python只能将字符串写入文本文件。若要写入数值数据,需要先用str()方法把其转换为字符串类型。
【实例】:
a=1
with open("D:\Code\Python\write.txt",'w') as file_object:
file_object.write(a)
【运行结果】:
Traceback (most recent call last):
File "d:\Code\Python\open.py", line 3, in <module>
file_object.write(a)
TypeError: write() argument must be str, not int
【正确代码】:
a=1
with open("D:\Code\Python\write.txt",'w') as file_object:
file_object.write(str(a))
5.写入多行
因为用write()写入的时候,python不会自动换行,所以我们要手动换行。
【实例】:
with open("D:\Code\Python\write.txt",'w') as file_object:
file_object.write("hello\n")
file_object.write("world\n")
【运行结果】:
6.附加到文件
写入文件的时候,将写入的内容添加到文件内内容之后,不把文件清空。
【实例】:
with open("D:\Code\Python\write.txt",'a') as file_object:
file_object.write("hello\n")
file_object.write("world\n")
【运行结果】:
o(* ̄▽ ̄*)ブ 感谢观看,希望对你有帮助!