在python中读取要列出的文本文件

在python中读取要列出的文本文件,python,Python,我想创建一个文本文件,其中包含以“,”分隔的正数/负数。 我想读取此文件并将其放入data=[]中。我已经写了下面的代码,我认为它工作得很好。 我想问你们是否知道一个更好的方法,或者它写得好吗 谢谢大家 #!/usr/bin/python if __name__ == "__main__": #create new file fo = open("foo.txt", "w") fo.write( "111,-222,-333");

我想创建一个文本文件,其中包含以“,”分隔的正数/负数。 我想读取此文件并将其放入
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()

您可以使用拆分,而不是循环:

#!/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]

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

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

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

file_obj = fo.read()#read your content into string
list_numbers = file_obj.replace('\n',',').split(',')#split on ',' and newline
print list_numbers

请参阅以获取有关工作代码的反馈。感谢您的帮助,我需要将数字附加为float以获取进一步的代码..我尝试了data.extend(float(line.split(',')),但它似乎不起作用。我需要类似于此的数据。append(float(float(tmp[i-count:i])line.split(','))返回一个列表,不能直接将浮点应用于该列表。如果要将其应用于该列表的每个元素,可以使用map方法:data.extend(map(float,line.split(','))或为了更好地理解它,map(float,line.split(','))表示[float(num)表示line.split(',')中的num]