’’‘read files’’'
with open('pi_digits.txt') as file_object:
contents = file_object.read()
print(contents)
print(contents.rstrip())
for line in file_object:
print(line.rstrip() + ".\n")
’’‘must reopen once’’'
with open('pi_digits.txt') as file_object:
lines = file_object.readlines()
pi_string =''
for line in lines:
pi_string +=line.rstrip()
print(pi_string)
print(len(pi_string))
with open('/users/apple/Desktop/pi_digits.txt') as file_object:
contents = file_object.read()
print(contents)
print(contents.rstrip())
lines = file_object.readlines()
for line in lines:
print(line.rstrip() + ".\n")
’’‘write files’’'
filename = 'programming.txt'
with open(filename, 'w') as file_object:
file_object.write("I love programming!")
file_object.write("\nI don't means that meaning!")
with open(filename, 'a') as file_object:
file_object.write("\nwhat do you meaning!\n")
file_object.write("I just use it make money!")
实验结果:
================ RESTART: /Users/apple/Documents/FileRead.py ================
3.1415926535
8979323846
2643383279
3.1415926535
8979323846
2643383279
3.141592653589793238462643383279
32
3.1415926535
8979323846
2643383279
3.1415926535
8979323846
2643383279