python 读取,写入文件

读取整个文件
# file_reader.py
# 在file_reader.py所在的目录中查找pi_digits.txt
with open('pi_digits.txt') as file_object: 
	contents = file_object.read() 
	print(contents)
逐行读取
# file_reader.py
# 在file_reader.py所在的目录中查找pi_digits.txt
with open('pi_digits.txt') as file_object: 
	for line in file_object: 
 		print(line)
创建一个包含文件各行内容的列表
filename = 'pi_digits.txt' 
with open(filename) as file_object: 
	lines = file_object.readlines() 
	
for line in lines: 
	print(line.rstrip())
使用文件的内容
filename = 'pi_digits.txt' 
with open(filename) as file_object: 
	lines = file_object.readlines() 
pi_string = '' 
for line in lines: 
	pi_string += line.rstrip() 
 
print(pi_string) 
print(len(pi_string))
相对路径
# Linux和OS X
with open('text_files/filename.txt') as file_object:

# windows 在文件路径中使用反斜杠(\)而不是斜杠(/)
with open('text_files\filename.txt') as file_object:
绝对路径
# Linux和OS X
file_path = '/home/ehmatthes/other_files/text_files/filename.txt' 
with open(file_path) as file_object:

# windows 在文件路径中使用反斜杠(\)而不是斜杠(/)
file_path = 'C:\Users\ehmatthes\other_files\text_files\filename.txt' 
with open(file_path) as file_object:
写入空文件
filename = 'programming.txt' 
# 写入的文件不存在,函数open()将自动创建它,如果指定的文件已经存在,Python将在返回文件对象前清空该文件
with open(filename, 'w') as file_object: 
	file_object.write("I love programming.")

读取模式(‘r’)、写入模式(‘w’)(覆盖掉)、附加模式(‘a’)或能够读取和写入文件的模式(‘r+’)

写入多行
filename = 'programming.txt' 
with open(filename, 'w') as file_object: 
	file_object.write("I love programming.\n") 
	file_object.write("I love creating new games.\n")
附加到文件
# 以附加模式打开文件,不会在返回文件对象前清空文件,而写入到文件的行都将添加到文件末尾
filename = 'programming.txt' 
with open(filename, 'a') as file_object: 
	file_object.write("I also love finding meaning in large datasets.\n") 
	file_object.write("I love creating apps that can run in a browser.\n")
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值