1. 读取文件_函数的使用
# _*_ coding:utf8 _*_
# 读取整个文件
# open()函数接受一个参数,是用来打开的文件 返回一个对象 存储在我们关键字 as 后面的变量中。
with open('pi_digits.txt') as file_object:
contents = file_object.read()
print(contents.rstrip())
# print(contents)
# 可以调用 open()和close()来打开和关闭文件 如果程序存在bug,那么close()函数没有调用,那么文件就将永远关闭不了
# 这个关闭可以让Python去确认,我们只管打开,关闭的动作交给Python来做,会在适当的时候去关闭
# print(contents.rstrip()) rstrip()是用来删除多出来的空行。
# read() 到大文件末尾时返回一个空字符串,将这个空字符串显示出来就是一个空行
# 在 linux和OS X 中 是使用 '/' 作为目录层级,在windows中使用 '\'
# 逐行读取
file_name = 'pi_digits.txt'
with open(file_name) as file_object:
for line in file_object:
print(line.rstrip())
print("**********")
# 创建一个包含文件各行内容的列表
with open(file_name) as file_object:
# readlines() 从文件中读取每一行,存储在一个列表中;然后该列表存储到变量lines中
lines = file_object.readlines()
print(lines)
for line in lines:
print(line.rstrip())
2. 使用文件内容
# _*_ coding:utf8 _*_
# 使用文件的内容
filename = 'pi_digits.txt'
with open(filename) as file_object:
lines = file_object.readlines()
pi_string = ''
for line in lines:
# pi_string += line.rstrip()
pi_string += line.strip()
print(pi_string[:20])
print("&&&&&&&&&&")
print(len(pi_string))
# Python将文件都解读为字符串,如果读取的是数字,想要作为数字使用,必须使用函数int() 将其转换为整数或者float()
# 对于你想处理的数据量,Python没有任何限制,只要系统内存足够多,想处理多少就处理多少