- 一、读取整个文件数据
- 二、文件路径
- 三、逐行读取
- 四、使用文件中的内容
- 五、写入文件
- 2. 写入多行文件
- 3. 添加到文件
with open('pi_digits') as file_object:
contents = file_object.read() 注:有了表示pi_digits的文件对象后,使用方法read()读取这个文件的全部容。
且作为长长的字符串赋给变量contents
print(contents)
#输出3.1415926535
#8979323846
#2643383279
注:关键字with在不再需要访问文件后将其关闭。注意到程序中调用了open(),但没有调用close()。也可以调用open()和close()来打开和关闭文件。但这样做,如果程序存在bug导致方法close()未执行,文件将不会关闭。,虽看似微不足道,但未妥善关闭文件可能导致数据丢失或受损;如果过早调用close(),你会发现需要使用文件时它已关闭(无法访问),这会导致更多的错误。所以为了避免以上问题的发生,使用上述结构,可以让Python去确定:你只管打开文件,并在需要时使用它,Python自会在合适的时候自动将其关闭。
二、文件路径file_path = 'C:/Users/2020/PycharmProjects/QtDesigner/former_Qt/pi_digits'
with open(file_path) as file_object:
contents = file_object.read()
print(contents)
#输出3.1415926535
#8979323846
#2643383279
注:此方法可以将文件在计算机的准确位置告诉Python,即绝对路径(可以读取系统中任何地方的文件)。
三、逐行读取filename = 'pi_digits'
with open(filename) as file_object:
for line in file_object:
print(line)
#输出3.1415926535
#8979323846
#2643383279
注:我们会发现,每打印一行,空白行更多了。为何会出现这些空白行呢?
因为在这个文件中,每行的末尾都有一个看不见的换行符,而函数调用print()也会加上一个换行符,因此每行末尾都有两个换行符,一个来自文件,另一个来自函数调用print()。怎样消除这些空白行呢?
可在函数调用print()中使用rstrip(),即print(line.rstrip())。
filename = 'pi_digits'
with open(filename) as file_object:
lines = file_object.readlines()
pi_string = '' 注:创建了一个变量pi_string,用于指向圆周率的值
for line in lines: 注:
# 使用一个循环将各行加入pi_string,并删除每行末尾的换行符
pi_string += line.rstrip()
print(pi_string)
print(len(pi_string))
#输出3.1415926535 8979323846 2643383279
#36
五、写入文件
保存数据的最简单的方式之一就是将其写入文件。
filename = 'programming'
with open(filename,'w') as file_object:
file_object.write("I love programming.")
#输出:生成一个programming.py文件。
2. 写入多行文件
filename = 'programming'
with open(filename,'w') as file_object:
file_object.write("I love programming.")
file_object.write("I love creating new games.")
#输出:生成一个programming文件,
文件内容为I love programming.I love creating new games.
注:会发现两行内容是挤在一起的,即函数write()不会在写入的文本末尾添加换行符。所以需要我们手动添加换行符“n”
filename = 'programming'
with open(filename,'w') as file_object:
file_object.write("I love programming.n")
file_object.write("I love creating new games.n")
#输出:生成一个programming文件,
#文件内容为I love programming.
#I love creating new games.
3. 添加到文件
filename = 'programming'
with open (filename,'a') as file_object:
file_object.write("I also like studying English.n")
file_object.write("I hope go aboard in the future.n")
#输出:生成一个programming文件,
#文件内容为I love programming.
#I love creating new games.
#I also like studying English.
#I hope go aboard in the future.



