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(* ̄▽ ̄*)ブ 感谢观看,希望对你有帮助!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库