繁体   English   中英

读取文本文件以在python中列出

[英]Read text file to list in python

我想创建一个文本文件,其中包含以“,”分隔的正/负数。 我想读取此文件并将其放入data = [] 我已经在下面编写了代码,我认为它很好用。 我想问你们是否知道更好的方法,或者写得好吗,谢谢大家

#!/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()

您可以使用以逗号作为分隔符的split方法:

fin = open('foo.txt')
for line in fin:
    data.extend(line.split(','))
fin.close()

除了遍历之外,您还可以使用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)

请注意,这会返回一个列表列表,每个列表都来自单独的一行。 在您的示例中,您只有一行。 如果您的文件始终只有一行,那么您可以只采用第一个元素data [0]

要将整个文件内容(正数和负数)放入列表中,可以使用分割线和分割线

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM