我有一个文本文件,其中填充了如下数据:
#n
44026533495303941500076737402297403862946691
#e
6969696
#f
37243759787836627691897628674719248256836857
最后,我想知道用变量n,e,f保存的数字
我试着逐行阅读它,但数据流只给了我一个字母一个字母,我的代码如下:
file = open(sys.argv[2]).read() # for getting file
for line in file:
print(line) # but it gives letter for letter
我的想法是举个例子
n = file[1]
e = file[5]
发布于 2018-06-25 22:54:31
很接近,但没有雪茄。
你应该去掉.read()
,it reads the whole file。这可能就是你想要的。
file = open(sys.argv[2]) # no .read() please
for line in file:
print(line) # now it gives the line
file.close() # don't forget to release the resource!
..。但这才是你真正想要的
with open(sys.argv[2], 'r') as input_file:
for line in input_file:
print(line)
通过使用with
关键字,您不必记住关闭资源!(here's a tutorial on it)。
此外,如果您在open
中指定'r'
,那么您打算对该文件执行的操作就会更明显一些。不是很重要,但推荐使用。
https://stackoverflow.com/questions/51028321
复制相似问题