我目前正在使用以下语句将文件的每一行写入列表
try:
list = []
with open(file, 'r') as f:
for l in f.readlines():
list.append(l)
except:
...
Run Code Online (Sandbox Code Playgroud)
虽然它工作得很好,我想知道是否有更多的pythonic方式来做到这一点?
编辑: 使用建议的更新
try:
my_list = []
with open(file, 'r') as f:
my_list = f.readlines()
except IOError:
...
Run Code Online (Sandbox Code Playgroud)
为什么不这样做:
try:
with open(file, 'r') as f:
lst = f.readlines()
except IOError:
print("File doesn't exist")
Run Code Online (Sandbox Code Playgroud)
f.readlines() 已经返回文件中所有行的列表.
或甚至更简单:
try:
with open(file, 'r') as f:
lst = list(f)
except IOError:
print("File doesn't exist")
Run Code Online (Sandbox Code Playgroud)