[英]Reading a list from a file
I want to read from a .txt
file, which has data saved as in list format. 我想从
.txt
文件中读取文件,该文件的数据另存为列表格式。
['http://www.example.com/?date=20080301',
'http://www.example.com/?date=20080302',
'http://www.example.com/?date=20080303']
I have the following code: 我有以下代码:
with open("test.txt", 'r') as file_name:
for urls in file_name:
for url in eval(urls):
print url
It worked well with exactly idential file (only different links) and now out of a sudden, it raises an exception: 它与完全相同的文件(仅不同的链接)一起使用时效果很好,但突然之间,它引发了一个异常:
File "<string>", line 1
['http://www.example.com/?date=20080301',
^
SyntaxError: unexpected EOF while parsing
Do you have any ideas? 你有什么想法?
Use ast.literal_eval()
: 使用
ast.literal_eval()
:
import ast
with open("test.txt", 'r') as file_name:
lists = ast.literal_eval(file_name.read())
for url in lists:
print url
It's much more efficient than using eval
because, and quoting from the docs, it "safely evaluate[s] an expression node or a string containing a Python expression." 它比使用
eval
更为有效,因为并引用了文档,它“安全地评估表达式节点或包含Python表达式的字符串”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.