python中读取文件和处理异常
读取文件
读取file.txt文件
使用关键字with时,open()返回的文件对象只在with代码块内可用。
with open('file.txt') as file_obj:
contents = file_obj.read()
print(contents)
#open('file.txt')返回一个表示文件file.txt的对象;这个对象被存储在file_obj中
在程序文件所在目录下的一个文件夹text_files:
在Linux和OS X中:with open(‘text_files/filename.txt’) as file_object:
Windows系统中:with open(‘text_files\filename.txt’) as file_object:
#file.txt
one
two
three
#逐行读取文件方法1
for line in open("file.txt"):
print (line)
#逐行读取文件方法2
filename = 'file.txt'
with open(filename) as file_object:
for line in file_object:
print(line)
---------------------------------------------------
one
two
three
#注意每行输出后的两行换行:在file.txt中,
#每行的末尾都有一个看不见的换行符,
#而print语句也会加上一个换行符,因此每行末尾都有两个换行符:
#一个来自文件,另一个来自print语句
python3 去除换行的三种方法
1.
print(line.rstrip())
2.
print(line.strip('\n'))
3.
f = open("file.txt")
line = f.readline()
while line:
print(line, end='')
line = f.readline()
f.close()
#三者输出均为
one
two
three
another example:
file1 = open('file.txt', 'r')
# 全部输入,打成一行
content = file1.readlines()
print(len(content))
print(content)
file1.close()
---------------------------------------------------
3
['one\n', 'two\n', 'three']
如果要在with代码块外访问文件的内容,可在with代码块内将文件的各行存储在列表中
filename = 'file.txt'
with open(filename) as file_object:
lines = file_object.readlines()#readlines读取每一行将其存储在列表中
text_string = ''
for line in lines:
text_string += line.strip()
print(text_string)
onetwothree
写入文件
filename = 'love_u.txt'
with open(filename, 'w') as file_object:
file_object.write("I love you.")
---------------------------------------------------
I love you.
open()的第一个实参–打开的文件的名称; 第二个实参–写入模式打开
Python只能将字符串写入文本文件
如果你要给文件添加内容,而不是覆盖原有的内容,可以附加模式打开文件:写入的行都将添加到文件末尾
filename = 'love_u.txt'
with open(filename, 'a') as file_object:
file_object.write(" I love being with you.\n")
---------------------------------------------------
-> I love you. I love being with you.
程序异常
try:
#do sth
except:
#可能出现的问题和相应的解决方式
#或者程序运行失败后啥都不做:
pass
else:
#执行语句
使用try-except代码块提供了两个重要的优点:避免让用户看到traceback;让程序能够继续分析能够找到的其他文件。
如果不捕获因错误情况的发生而引发的FileNotFoundError异常,用户将看到完整的traceback,而程序将在尝试分析失败后停止运行——后面的代码将不再被考虑。
JSON(JavaScript Object Notation)
import json
# 列表
name = ['Alice', 'Kate', 'Bob']
# 字典
language = {
'Python': 'leaning',
'Java': 'expert'
}
# 元组
number = (3, 2, 1)
with open('prefered_language.json', 'w') as f1:
json.dump(name, f1)
# json.dump(language, f1)
# json.dump(number, f1)
filename = 'prefered_language.json'
with open(filename) as f_obj:
txt = json.load(f_obj)
print(txt)
>>> ['Alice', 'Kate', 'Bob']