1、open()函数用于打开一个文件
with open("pi_digits.txt") as file_object:
contents = file_object.read()
print(contents)
2、还可以按行来读取文件里的内容
file_name = "pi_digits.txt"
with open(file_name) as file_object:
for line in file_object:
print(line)
3、open()返回的文件只能在with代码块里使用,如果要在外部使用要将文件内保存在一个列表中。之后用for循环将列表里的数据赋给一个变量,就可以使用了。
file_name = "pi_digits.txt"
with open(file_name) as file_object:
lines = file_object.readlines()
pi_string = ""
for line in lines:
pi_string = pi_string + line.strip()
print(pi_string)
print(len(pi_string))
4、将一个文件里的“c”都替换为“python”
file_name = "c.txt"
with open(file_name) as file_object:
lines = file_object.readlines()
source_string = "c"
target_string = "Python"
text = ""
for line in lines:
if source_string in line:
line = line.replace(source_string, target_string)
text = text + line.strip()
print(text)
print(len(text))