我使用以下代码在Python中导入数据:
one=[]
two=[]
three=[]
four=[]
five=[]
six=[]
x=0
for line in open('text.txt', 'r'):
if x==2:
column0, column1, column2, column3, column4, column5 = line.split(',')
else:
column0, column1, column2, column3, column4, column5 = line.split(' ')
one.append(column0)
two.append(column1)
three.append(column2)
four.append(column3)
five.append(column4)
six.append(column5)
x=x+1此代码导入此文本文件:
1 2 3 4 5 6
1 2 3 4 5 6
1,2,3,4,5,6
1 2 3 4 5 6
1 2 3 4 5 6但是我在如何导入下面的内容时遇到了很多麻烦
1 2 3 4 5 6
1 2 3 4 5 6
1,2,3,
4,5,6
1 2 3 4 5 6
1 2 3 4 5 6即使数据在第三行有一个分隔符,我也希望它以与第一个文本文件相同的方式导入。我尝试按行导入,然后使用第三行的变量数,但我无法使其正常工作。
有没有人知道任何资源或例子,或者可以帮助你?谢谢!
发布于 2012-03-17 11:32:03
这里有一种方法可以把台词弄对。这不是一个完整的答案,但我认为它解决了你可能遇到的任何问题
fh = open('Documents/import.txt').read()
for line in fh.split('\n'):
print line.strip()
splits = line.split()
if len(splits) ==1 and splits[0]== line.strip():
splits = [item for item in line.strip().split(',') if item]
print splits哦..。没有读到你想要的东西试试这个
fh = open('Documents/import.txt').read()
the_list = []
for line in fh.split('\n'):
print line.strip()
splits = line.split()
if len(splits) ==1 and splits[0]== line.strip():
splits = line.strip().split(',')
if splits:the_list.append(splits)
for i in range(len(the_list)):
print the_list[i]
if the_list[i][-1]=='':
the_list[i].pop(-1)
the_list[i].extend(the_list[i+1])
i += 1
print the_list发布于 2012-03-17 11:15:06
csv module。使用适当的delimiter选项参数,它还将读取以空格分隔的数据,或者您可以在读取数据之前将空格替换为逗号。发布于 2012-03-17 11:17:47
行for line in open('text.txt', 'r'):遍历文件中的各行。它不会注意你的逗号。
如果您希望按元素而不是按行进行迭代,则必须使用不同的循环。
你可能想读这个问题:How to read numbers from file in Python?它展示了如何一次读取一个数字,忽略换行符。您需要使用pass a parameter to the split function命令来告诉它跳过逗号和空格。
附注:在您当前的代码中,if x==2:什么也不做。如果您真的想计算行数,则需要使用enumerate函数。
https://stackoverflow.com/questions/9746927
复制相似问题