Python 从文件中读取列表
我想从Python 从文件中读取列表,python,list,python-2.7,with-statement,Python,List,Python 2.7,With Statement,我想从.txt文件中读取数据,该文件的数据以列表格式保存 ['http://www.example.com/?date=20080301', 'http://www.example.com/?date=20080302', 'http://www.example.com/?date=20080303'] 我有以下代码: with open("test.txt", 'r') as file_name: for urls in file_name: for url in
.txt
文件中读取数据,该文件的数据以列表格式保存
['http://www.example.com/?date=20080301',
'http://www.example.com/?date=20080302',
'http://www.example.com/?date=20080303']
我有以下代码:
with open("test.txt", 'r') as file_name:
for urls in file_name:
for url in eval(urls):
print url
它在完全相同的文件(仅不同的链接)中运行良好,现在突然出现了一个异常:
File "<string>", line 1
['http://www.example.com/?date=20080301',
^
SyntaxError: unexpected EOF while parsing
文件“”,第1行
['http://www.example.com/?date=20080301',
^
SyntaxError:分析时出现意外的EOF
你有什么想法吗?使用:
它比使用eval
更有效,因为它“安全地计算表达式节点或包含Python表达式的字符串”。使用:
它比使用
eval
更有效,因为它“安全地计算表达式节点或包含Python表达式的字符串”,并引用文档首先要避免格式?现在已经解决了,但是避免格式是什么意思?不要向文件中写入Python列表文字。而是使用换行符编写单独的URL。首先要避免格式?现在已经解决了,但是避免格式是什么意思?不要向文件中写入Python列表文字。W使用换行符来编写单独的URL。
import ast
with open("test.txt", 'r') as file_name:
lists = ast.literal_eval(file_name.read())
for url in lists:
print url