【问题标题】:How to import data from a .txt file into arrays in python如何将.txt文件中的数据导入python中的数组
【发布时间】:2019-11-22 15:25:23
【问题描述】:

我正在尝试从一个 .txt 文件中导入数据,该文件包含由制表符分隔的四列,并且有数千行长。这是文档开头的样子:

Data info
File name: D:\(path to file)
Start time: 6/26/2019 15:39:54.222
Number of channels: 3
Sample rate: 1E6
Store type: fast on trigger
Post time: 20
Global header information: from DEWESoft
Comments: 

Events
Event Type  Event   Time    Comment
1   storing started at  7.237599    
2   storing stopped at  7.257599    


Data1
Time    Incidente   Transmitida DI 6    
s   um/m    um/m    -   
0   2.1690152   140.98599   1
1E-6    2.1690152   140.98599   1
2E-6    4.3380303   145.32402   1
3E-6    4.3380303   145.32402   1
4E-6    -2.1690152  145.32402   1

我有几个这样的文件,我想循环并存储在一个单元格/列表中,每个单元格/列表项包含四列。之后,我只需使用该单元格/列表来循环绘制数据。

看到pandas库很合适,但是不明白怎么用。

fileNames = (["Test1_0001.txt", "Test2_0000.txt", "Test3_0000.txt",
    "Test4_0000.txt", "Test5_0000.txt", "Test6_0001.txt", "Test7_0000.txt",
    "Test8_0000.txt", "Test9_0000.txt", "Test10_0000.txt", "RawblueMat_0000.txt"])

folderName = 'AuxeticsSHPB\\' #Source folder for all files above

# Loop trough each source document
for i in range(0,len(fileNames)):
    print('File location: '+folderName+fileNames[i])

    # Get data from source as arrays, cut out the first 20 lines
    temp=pd.read_csv(folderName+fileNames[i], sep='\t', lineterminator='\r', 
                     skiprows=[19], error_bad_lines=False)

    # Store data in list/cell
    # data[i] = temp   # sort it

这是我尝试过的东西,但没有用,真的不知道如何进行。我知道有一些关于这个问题的文档,但我是新手,需要一些帮助。

尝试上述方法时出现错误:

ParserError: Error tokenizing data. C error: Expected 1 fields in line 12, saw 4

【问题讨论】:

  • 你有一个元组列表,([ ... ]),也许这是一个原因?另外,为什么是skiprows=[19],而不是skiprows=19
  • @MichaelO。 skiprows=[19] 是问题所在,感谢您的帮助!现在可以使用了。

标签: python arrays pandas numpy scipy


【解决方案1】:

所以这是一个简单的修复,只需从skiprows=[19] 中移除大括号。

鳕鱼现在看起来像这样并且可以工作。

fileNames = ["Test1_0001.txt", "Test2_0000.txt", "Test3_0000.txt",
    "Test4_0000.txt", "Test5_0000.txt", "Test6_0001.txt", "Test7_0000.txt",
    "Test8_0000.txt", "Test9_0000.txt", "Test10_0000.txt", "RawblueMat_0000.txt"]

folderName = 'AuxeticsSHPB\\' #Source folder for all files above

# Preallocation
data = []

for i in range(0,len(fileNames)):
    temp=pd.read_csv(folderName+fileNames[i], sep='\t', lineterminator='\r', 
                     skiprows=19)
    data.append(temp)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-30
    • 1970-01-01
    • 2018-12-23
    • 2020-11-03
    • 2012-10-23
    • 1970-01-01
    • 1970-01-01
    • 2020-04-06
    相关资源
    最近更新 更多