首页 > 解决方案 > 使用 Python 读取带有分号分隔文本的 TXT 文件

问题描述

文本文件中的示例数据如下:

从表1中选择*;从表2中选择*;从表 3 中选择 *;从表 4 中选择 *

我想阅读此文本并在分号(;)处分成多行并分别处理每一行。基本上每一行都代表一个选择查询,我需要对数据库逐一查询

我尝试了下面的代码但收到错误:AttributeError:'list' object has no attribute 'split'

ListData = open(FilePath).readlines()
for line in ListData.split(';'):


data.append(line)

也尝试了下面的代码,但出现 AttributeError 错误:'_io.TextIOWrapper' object has no attribute 'split'

with open(SQLFilePath) as f:
    for line in f.split(';'):
      data.append(line)

谢谢

标签: python-3.xpandaslistdataframe

解决方案


尝试使用 for()。例如:

text='Select * from Table1; Select * from Table2; select * from table3;Select * from table4'
for t in text.split(';'):
    print(t)

回答:

Select * from Table1
 Select * from Table2
 select * from table3
Select * from table4

如果从文件中读取数据,可以使用 pandas:

import pandas as pd
df=pd.read_csv(r'C:\Users\Desktop\test.txt', header = None)
t=[]
for index, row in df.itertuples():
    t=t+str(row).split(';')

安慰:

print(t)
['Select * from Table1', ' Select * from Table2', ' select * from table3', 'Select * from table4', 'Select * from Table1', ' Select * from Table2', ' select * from table3', 'Select * from table4']

推荐阅读