[英]Reading a txt file and saving individual columns as lists
I am trying to read a .txt file and save the data in each column as a list.我正在尝试读取 .txt 文件并将每列中的数据保存为列表。 each column in the file contains a variable which I will later on use to plot a graph.
文件中的每一列都包含一个变量,稍后我将使用它来绘制图形。 I have tried looking up the best method to do this and most answers recommend opening the file, reading it, and then either splitting or saving the columns as a list.
我已尝试查找执行此操作的最佳方法,大多数答案建议打开文件,阅读它,然后将列拆分或另存为列表。 The data in the .txt is as follows -
.txt中的数据如下——
0 1.644231726
0.00025 1.651333945
0.0005 1.669593478
0.00075 1.695214575
0.001 1.725409504
the delimiter is a space ''
or a tab '\\t'
.分隔符是空格
''
或制表符'\\t'
。 I have used the following code to try and append the columns to my variables -我使用以下代码尝试将列附加到我的变量中 -
import csv
with open('./rvt.txt') as file:
readfile = csv.reader(file, delimiter='\t')
time = []
rim = []
for line in readfile:
t = line[0]
r = line[1]
time.append(t)
rim.append(r)
print(time, rim)
However, when I try to print the lists, time and rim, using print(time, rim)
, I get the following error message -但是,当我尝试使用
print(time, rim)
打印列表、时间和边缘print(time, rim)
,我收到以下错误消息 -
r = line[1]
IndexError: list index out of range
I am, however, able to print only the 'time' if I comment out the r=line[1]
and rim.append(r)
parts.但是,如果我注释掉
r=line[1]
和rim.append(r)
部分,我只能打印“时间”。 How do I approach this problem?我该如何解决这个问题? Thank you in advance!
先感谢您!
I would suggest the following:我建议如下:
import pandas as pd
df=pd.read_csv('./rvt.txt', sep='\t'), header=[a list with your column names])
Then you can use list(your_column) to work with your columns as lists然后您可以使用 list(your_column) 将您的列作为列表使用
The problem is with the delimiter.问题在于分隔符。 The dataset contain multiple space ' '.
数据集包含多个空格“ ”。
When you use '\\t'
and print line
you can see it's not separating the line with the delimiter.当您使用
'\\t'
并打印line
您可以看到它没有用分隔符分隔该行。
eg:例如:
['0 1.644231726']
['0.00025 1.651333945']
['0.0005 1.669593478']
['0.00075 1.695214575']
['0.001 1.725409504']
To get the desired result you can use要获得所需的结果,您可以使用
(space) as delimiter and filter
the empty values: (space) 作为分隔符并
filter
空值:
readfile = csv.reader(file, delimiter=" ")
time, rim = [], []
for line in readfile:
line = list(filter(lambda x: len(x), line))
t = line[0]
r = line[1]
Here is the code to do this:这是执行此操作的代码:
import csv
with open('./rvt.txt') as file:
readfile = csv.reader(file, delimiter=” ”)
time = []
rim = []
for line in readfile:
t = line[0]
r = line[1]
time.append(t)
rim.append(r)
print(time, rim)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.