[英]Read text file to list in python
I want to create a text file which contains positive/negative numbers separated by ','. 我想创建一个文本文件,其中包含以“,”分隔的正/负数。 i want to read this file and put it in
data = []
. 我想读取此文件并将其放入
data = []
。 i have written the code below and i think that it works well. 我已经在下面编写了代码,我认为它很好用。 I want to ask if you guys know a better way to do it or if is it well written thanks all
我想问你们是否知道更好的方法,或者写得好吗,谢谢大家
#!/usr/bin/python
if __name__ == "__main__":
#create new file
fo = open("foo.txt", "w")
fo.write( "111,-222,-333");
fo.close()
#read the file
fo = open("foo.txt", "r")
tmp= []
data = []
count = 0
tmp = fo.read() #read all the file
for i in range(len(tmp)): #len is 11 in this case
if (tmp[i] != ','):
count+=1
else:
data.append(tmp[i-count : i])
count = 0
data.append(tmp[i+1-count : i+1])#append the last -333
print data
fo.close()
Instead of looping through, you can just use split: 除了遍历之外,您还可以使用split:
#!/usr/bin/python
if __name__ == "__main__":
#create new file
fo = open("foo.txt", "w")
fo.write( "111,-222,-333");
fo.close()
#read the file
with open('foo.txt', 'r') as file:
data = [line.split(',') for line in file.readlines()]
print(data)
Note that this gives back a list of lists, with each list being from a separate line. 请注意,这会返回一个列表列表,每个列表都来自单独的一行。 In your example you only have one line.
在您的示例中,您只有一行。 If your files will always only have a single line, you can just take the first element, data[0]
如果您的文件始终只有一行,那么您可以只采用第一个元素data [0]
To get the whole file content(numbers positive and negative) into list you can use split and splitlines 要将整个文件内容(正数和负数)放入列表中,可以使用分割线和分割线
file_obj = fo.read()#read your content into string
list_numbers = file_obj.replace('\n',',').split(',')#split on ',' and newline
print list_numbers
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.