[英]About file I/O in python
我想读取一个txt文件并将其存储为字符串列表。 这是我自己提出的一种方式。 看起来很笨拙。 有什么更好的方法吗? 谢谢。
import re
import urllib2
import re
import numpy as np
url=('http://quant-econ.net/_downloads/graph1.txt')
response= urllib2.urlopen(url)
txt= response.read()
f=open('graph1.txt','w')
f.write(txt)
f.close()
f=open('graph1.txt','r')
nodes=f.readlines()
我尝试了下面提供的解决方案,但是它们实际上都返回了与我之前的代码不同的东西。 这是split()产生的字符串
'node0, node1 0.04, node8 11.11, node14 72.21'
这是我的代码产生的
'node0, node1 0.04, node8 11.11, node14 72.21\n'
问题是当我尝试处理字符串列表时没有'\\ n'的问题,它将遇到一些索引错误。 “ row = index [0] IndexError:列表索引超出范围”
for node in nodes:
index = re.findall('(?<=node)\w+',node)
index = map(int,index)
row = index[0]
del index[0]
根据文档 , response
已经是一个类似于文件的对象:您应该能够执行response.readlines()
。
但是对于那些确实需要创建中间文件的问题,您想使用io.StringIO
看分裂 。 所以:
nodes = response.read().split("\n")
编辑:或者,如果您要避免\\r\\n
换行符,请使用splitlines 。
nodes = response.read().splitlines()
尝试:
url=('http://quant-econ.net/_downloads/graph1.txt')
response= urllib2.urlopen(url)
txt= response.read()
with open('graph1.txt','w') as f:
f.write(txt)
nodes=txt.split("\n")
如果您不想要该文件,这应该可以工作:
url=('http://quant-econ.net/_downloads/graph1.txt')
response= urllib2.urlopen(url)
txt= response.read()
nodes=txt.split("\n")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.