- 新建文件 pi_digits.txt 及内容:
3.1415926535
8979323846
2643383279
- 读取整个文件
with open("pi_digits.txt") as file_object:
contents = file_object.read()
print(contents.rstrip())
- 逐行读取
filename = 'pi_digits.txt'
with open(filename) as file_object:
for line in file_object:
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.strip()
print("pi_string ", pi_string, "length is:", len(pi_string))
实例输出结果:
- 圆周率值中前一百万位中是否包含你的生日
filename = 'pi_million_digits.txt'
with open(filename) as file_object:
lines = file_object.readlines()
pi_string = ""
for line in lines:
pi_string += line.strip()
birthday = input("Enter your birthday, in the form mmddyy: ")
if birthday in pi_string:
print("Your birthday appears in the first million digits of pi!")
else:
print("Your birthday does not appear in the first million digits of pi.")
- 写入文件
filename = 'programming.txt'
with open(filename, 'w') as file_object:
file_object.write("I love programming 1.\n")
file_object.write("I love programming 2.")
- 附加到文件
filename = 'programming.txt'
with open(filename, 'a') as file_object:
file_object.write("I love programming 1.\n")
file_object.write("I love programming 2.\n")
本文参考自 《Python 编程:从入门到实践》