【发布时间】:2020-01-04 01:35:34
【问题描述】:
我正在尝试阅读大约 2000 个 .txt 文件,它们的列并不相同。我只想选择所有文件中的公共标题并将它们保存到 csv 文件中以上传到 MySQL 数据库中。 我需要帮助来解析这些文件以仅选择我需要的列。我只需要以下列:code、startDate、startTime、endDate、endTime、s、number。 startDate 和 endDate 之后的时间列在文件中没有标题。我刚刚将它们命名为“startTime”和“endTime”
作为插图
file1 样本:
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
file2 示例:
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:])
当我检查完整的数据框时,它得到的列数超过了我需要的列数,因为每个文件中的列数可能不同。
【问题讨论】:
-
很难从您的文件样本中看出,但这些文件可能是固定宽度的文本文件吗?
-
是的,先生,这是可能的。