Python基础— 文件
1.读取文件
with open('pi_digits.txt') as file_object:
'''到当前目录中查找文件'''
contents = file_object.read()
print(contents)
#read()到达文件末尾时返回一个空字符串,打印出来多一空行,要删除多余的空行,使用rstrip()
# print(contents.rstrip())
'''相对路径下'''
with open('text_files\pi_digits.txt') as file_object:
contents=file_object.read()
print(contents)
'''绝对路径下'''
file_path='H:\pythonpj\\text_files\pi_digits.txt'
with open(file_path) as file_object:
contents=file_object.read()
print(contents)
'''逐行读取'''
file_name='pi_digits.txt'
''''''
with open(file_name) as file_object:
for line in file_object:
print(line) #逐行打印会每行多一空行
with open(file_name) as file_object:
for line in file_object:
print(line.rstrip()) #逐行打印消去空行
#创建一个包含文件各行内容的列表
#readlines() 从文件中读取每一行,并将其存储在一个列表中
filename='pi_digits.txt'
with open(filename) as file_object:
lines=file_object.readlines()
for line in lines:
print(line.strip())
'''处理FileNotFoundError异常
'''
f_name='a.txt'
try:
with open(f_name) as f_obj: # file_object 可以简写成 f_obj
contents=f_obj.read()
except FileNotFoundError:
msg = "Sorry ,the file " + f_name + " does not exit."
print(msg)
2.使用文件的内容
'''使用文件的内容'''
filename='pi_digits.txt'
with open(filename) as file_object:
lines=file_object.readlines()
pi_string = ''
for line in lines:
pi_string += line.rstrip() #rstrip() 可删除每行末尾的换行符
print(pi_string)
print(len(pi_string))
pi_string2=''
for line in lines:
pi_string2 += line.strip() #strip() 删除所有的空格
print(pi_string2)
print(len(pi_string2))
print(pi_string2[:22]+'...') #输出小数点后20位
#检查输入的字符串是否包含在文件中
birthday=input("Enter your birthday: ")
if birthday in pi_string2:
print("yes!")
else:
print("no!")
3.写入文件
#写入空文件
filename='programming.txt'
'''open(filename,'w'/'r'/'a')提供两个实参,第一个是打开文件的名称,第二个系统默认是只读模式打开文件
若以‘w’模式打开时,如果指定的文件已经存在,python将在返回文件对象前清空该文件
'a'方式给文件添加内容,不是覆盖原有的内容
'''
with open(filename,'w') as file_object:
file_object.write("I love programming~")
file_object.write("I love creating new games")
'''write()不会在写入的文本末尾添加换行符'''
file_object.write("I love python\n")
file_object.write("I love java")
"""I love programming~I love creating new gamesI love python
I love java
"""
'''
with open(filename) as file_object:
print(file_object.read())
'''
with open(filename,'a') as file_object:
file_object.write("I also love C++\n")
file_object.write("Go\n")