文章内容不再更新,因为内容已经写入Gitee仓库,只在仓库更新
地址
3.1415926535
8979323846
2643383279
文件
读文件
文件的内容读取到内存 解读为字符串 如果是数值要计算的话 int() float()
# 读取整个文件
filename = "D:\demo.js"
# with open(filename) as file_object:
# contents = file_object.read()
# print(contents.rstrip())
#逐行读取
# with open(filename) as file_object:
# for line in file_object:
# print(line.rstrip())
# readline() 从文件中读取每一个字,并将其存储在一个列表中 然后存在lines
# readlines() 从文件中读取每一行,并将其存储在一个列表中 然后存在lines
with open(filename) as file_object:
lines = file_object.readlines()
for line in lines:
print(line.rstrip())
with open('re.txt','r',encoding='utf-8') as file_object:
contents = file_object.read() #有readline()
print(contents)
#utf-8格式打开文档
f = open(r're.txt','r',encoding='utf-8')
f.seek(0,0) # 重新设置文件读取指针到开头
for each_line in f: # 逐行读取
print(each_line.rstrip()) # rstrip 删除多余空白行
f.close()
#以二进制打开文件,然后对读取的内容进行utf-8编码
f = open(r're.txt','rb')
f.seek(0,0)
for each_line in f:
print(each_line.decode('utf-8'))
f.close()
#查看圆周率中包含自己生日吗?
with open('pi_million_digits.txt') as file_object:
lines = file_object.readline()
pi_string = ""
for line in lines:
pi_string += line.strip()
birthday = input("Enter you birthday :") # 970104
if birthday in pi_string:
print('yes')
else:print('not')
写
filename = 're.txt'
with open(filename, 'a') as file_object: #附加 a 单纯的覆盖 w
file_object.write("I also love finding meaning in large datasets.\n")
file_object.write("I love creating apps that can run in a browser.\n")
name = input("What's your name? ")
with open(filename, 'a') as f:
f.write(name)
计算一个文件大致有多少个单词
def count_words(filename):
"""Count the approximate number of words in a file."""
try:
with open(filename,encoding='utf-8') as f_obj:
contents = f_obj.read()
except FileNotFoundError:
pass
else:
# Count approximate number of words in the file.
words = contents.split()
num_words = len(words)
print("The file " + filename + " has about " + str(num_words) + " words.")
filenames = ['re.txt','pi_million_digits.txt'] #,'pi_million_digits.txt'
for filename in filenames:
count_words(filename)
The file re.txt has about 21 words.
The file pi_million_digits.txt has about 10000 words.