《Python编程从入门到实践》日记Day_9
第十章 文件
①从文件中读取数据
- 读取整个文件
with open("pi.txt") as file_object:
contents = file_object.read()
print(contents)
注意:你所定义的txt文件需要保存在py路径下,(在左侧的索引能检测到你输入的txt文件),这样才能read。
函数open()。只有先打开文件才能访问它。函数open()接受一个参数,即要打开文件的名称。关键字with在不需要访问文件后将其关闭。你也可以调用open()和close()来打开和关闭文件。
但通过使用关键字with可以让Python去确定你只管打开文件并在需要时使用它。Python会在适合的时候自动将其关闭。
输出会多一个空行,因为read在文件末尾时返回一个空的字符串,这个空字符串显示出来就是一个空行。可在print语句中使用rstrip()。
print(contents.rstrip())
- 读取整个文件
#Pycharm\File_txt下的pi.txt#
with open("File_txt\pi.txt") as file_object:
#绝对文件路径
with open("E:\A-桌面-Flies\Pycharm\File_txt\pi.txt") as file_object:
contents = file_object.read()
print(contents.rstrip())
- 逐行读取
filename = "pi.txt"
with open(filename) as file_object:
for line in file_object:
print(line.rstrip())
3.145781211515613513
520.1314
- 创建一个包含文件各行内容的列表
filename = "pi.txt"
with open(filename) as file_object:
lines = file_object.readlines()
for line in lines:
print(line.rstrip())
print(lines)
######
3.145781211515613513
520.1314
['3.145781211515613513\n', '520.1314\n']
- 使用文件中的内容
filename = "pi.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))
####
3.145781211515613513520.1314
28
读取文本文件时,Python将其中的所有文本解读为字符串,需要使用函数int将需要的数字转化为整型或者float。
- 包含一百万位的大型文件
filename = "pi.txt"
with open(filename) as file_object:
lines = file_object.readlines()
pi_string = ''
for line in lines:
pi_string += line.rstrip()
print(pi_string[:50] + '...')
print(len(pi_string))
####
3.145781211515613513578121151561351357812115156135...
1900
这就有点类似列表中的切片操作。
- 对文件内容进行分析
filename = "pi.txt"
with open(filename) as file_object:
lines = file_object.readlines()
pi_string = ''
for line in lines:
pi_string += line.rstrip()
while True:
date = input("Please enter 3 numbers at will.")
if date in pi_string:
print('In the file.')
break
else:
print('Not in the file.')
####
Please enter 3 numbers at will.454
Not in the file.
Please enter 3 numbers at will.111
Not in the file.
Please enter 3 numbers at will.154
Not in the file.
Please enter 3 numbers at will.151
In the file.
②写入文件
1.写入空文件
filename = "programming.txt"
with open(filename, 'w') as file_object:
file_object.write("I love duoduo.")
2.写入多行
filename = "programming.txt"
with open(filename, 'w') as file_object:
file_object.write("I love duoduo.\n")
file_object.write("But he don't konw.")
3.附加到文件
给文件添加内容,而不是覆盖原有的内容。
可以在附加模式打开文件,你以附件模式打开文件时,Python不会再返回文件对象前清空文件,而你写入到文件的行都将添加到文件末尾。如果指定文件不存在,Python将为你创建一个空文件。
filename = "programming.txt"
with open(filename, 'a') as file_object:
file_object.write("I love peipi.\n")
file_object.write("But she don't konw.")
感兴趣可以多试几次,蛮好玩的😁