python - 如何读取多个缺少标题和不需要的列的 .txt 文件

标签 python pandas csv

我正在尝试读取大约 2000 个 .txt 文件,这些文件并不都具有相同的列。我只想选择所有文件中的公共(public) header ,并将它们保存到 csv 文件中,以便上传到 MySQL 数据库中。 我需要帮助解析这些文件以仅选择我需要的列。我只需要以下列:代码、开始日期、开始时间、结束日期、结束时间、s、数字。 startDate 和 endDate 之后有时间列,这些列在文件中没有标题。我刚刚将它们命名为“startTime”和“endTime”

作为说明

文件 1 示例:


code                         startDate        endDate          s   number
-------------------------------------- ------------------- ------------------- - ----------
4000                                   23-04-2010 00:00:00 23-04-2010 00:14:59 E          1
4001                                   23-04-2010 00:00:00 23-04-2010 00:14:59 E          0
4002                                   23-04-2010 00:00:00 23-04-2010 00:14:59 E          0
4003                                   23-04-2010 00:00:00 23-04-2010 00:14:59 E         0

文件2示例:

code                         lineNum                         startDate        endDate          s   number id description
-------------------------------------- -------------------------------------- ------------------- ------------------- - ---------- ------------------ ----------------------------------------------------------------------------------------------------
3000                                   2111201                                31-10-2010 05:45:00 31-10-2010 05:59:59 E          9                311 CAPITAL
3000                                   2111201                                31-10-2010 05:45:00 31-10-2010 05:59:59 E          4               1411 USUARIO FRECUENTE
3000                                   2111201                                31-10-2010 05:45:00 31-10-2010 05:59:59 E          1               7071 FUNCIONARIO
3000
file_list = [file1, file2,...]

datalist = []
for file in file_list[]:
    with open(file,'r') as f:
        reader = f.readlines()
        for line in reader:
            #use regex to search for only rows with text and numbers
            if re.search(r'[0-9a-zA-Z]', line):
                datalist.append(line.strip().split())
    header = datalist[0]
    try:
        repeatingHeaderIndx = datalist[1:].index(header) + 1
        #remove repeating header from data using index  
        datalist.pop(repeatingHeaderIndx)
    except:
        pass      
df = pd.DataFrame(datalist[1:])

当我检查完整的数据框时,它获得的列数超出了我需要的列数,因为每个文件中的列数可能不同。

最佳答案

您可以修改正则表达式以仅匹配包含任一列名称的行-

obj = re.compile(r'\b(code|startDate|startTime|endDate|endTime|s|number)\b')
with open('words.txt', 'r') as reader:
   for line in reader:
       match = obj.findall(line)
       datalist.append(match)

所以你的代码应该看起来像 -

file_list = [file1, file2,...]
obj = re.compile(r'\b(code|startDate|startTime|endDate|endTime|s|number)\b')

datalist = []
for file in file_list[]:
    with open(file,'r') as f:
        reader = f.readlines()
        for line in reader:
            match = obj.findall(line)
            if match:
                datalist.append(match)
header = datalist[0]
try:
    repeatingHeaderIndx = datalist[1:].index(header) + 1
    #remove repeating header from data using index  
    datalist.pop(repeatingHeaderIndx)
except:
    pass      
df = pd.DataFrame(datalist[1:])

关于python - 如何读取多个缺少标题和不需要的列的 .txt 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57732809/

相关文章:

python - 编译Windows的Blender时出错-找不到OSL

python - 如何在一行代码中将 pandas 中的 float 转换为不包括 NaN 的字符串?

python - 使用 Python 重构 CSV 文件

Python CSV 删除空行

python - 为所有网格设置 xticklabels,用于使用 col_wrap 的 seaborn catplot 创建的图

javascript - 如何在 Bokeh/Python/Pywidgets 中使一个 slider /小部件更新多个绘图?

python - pandas 中列名称的可变组合

python - 遍历多个列以找到一个值,然后创建一个新列

multithreading - 用于在 Julia 中读取 CSV 文件的多线程

python - 监控文件变化 - Asyncio 和 Flask