在python中读取一个txt文件,观察之间有多个空格

2024-09-30 14:36:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个非常不寻常的txt文件,其中观察值被大量空格分隔,我的代码出现以下错误:

你知道吗更新:问题是因为我有所有这些乱七八糟的txt文件的顶部,我不知道如何处理除了使用枚举和跳行,问题是我有超过50个文件,我必须解析。。你知道吗

LocationCode IndustryCode OccupationCode TotalResults SourceCode           CreatedOn                   UpdatedOn

-------------- --------------------------------------- 
---------------------    ------ -------------------------------------------------- ------------ -----     ------- -------------- ------------ ---------- ---------------------------      ---------------------------
        rftergt------------------




error:IndexError: list index out of range

请参见txt文件中的几行:

8969758        35175                                   2018-05-03 18:32:11.9629608                                                    21CIWS       130          NULL           2685         JSW        2018-05-03 18:32:12.1213757 2018-05-03 18:32:12.1213757

8969759        37132                                   2018-05-03 18:32:12.3444130                                                    49TWNQ       NULL         NULL           654          JSW        2018-05-03 18:32:12.5069561 2018-05-03 18:32:12.5069561

8969761        319150                                  2018-05-03 18:32:16.6022496                                                    49MCKY       NULL         NULL           678          JSW        2018-05-03 18:32:16.7648819 2018-05-03 18:32:16.7648819

我的代码:

first_row = True
with open("10_JobSearchLog.txt" ,'r')as f:

    reader = csv.reader(f , delimiter =",")
    header = next(reader)

    for line in f:
        if first_row:
            first_row = False
            continue

        line = line.strip().split(" ")
        print(line)
        buck1,buck2,buck3,buck4 = line[0],line[1],line[3],line[4]

Tags: 文件代码txt错误linenullreaderrow
2条回答

通过将您的代码修改为

with open(filename) as infile:
    header = next(infile)  #Header
    for line in infile:
        if line.strip():             #Check if line is not empty
            line = line.split()      #Split line by space
            if len(line) >= 4:
                buck1,buck2,buck3,buck4 = line[0],line[1],line[3],line[4]
                print(buck1,buck2,buck3,buck4)

通过这样做,您可以确保如果文件的任何部分不符合您的特定格式,您将跳过该行,因此您将跳过那些杂乱的标题:)

使用。你知道吗

with open(filename) as infile:
    header = next(infile)  #Header
    for line in infile:
        if line.strip():             #Check if line is not empty
            line = line.split()      #Split line by space
            buck1,buck2,buck3,buck4 = line[0],line[1],line[3],line[4]
            print(buck1,buck2,buck3,buck4)

输出:

('8969759', '37132', '18:32:12.3444130', '49TWNQ')
('8969761', '319150', '18:32:16.6022496', '49MCKY')

相关问题 更多 >