python-3.x - 使用 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)
谢谢
解决方案
尝试使用 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']
推荐阅读
- ruby - 使用自定义模式对树类进行冰糕类型检查?
- access-control - AWS Quicksight 对 Elasticsearch 数据的精细访问控制文档级安全性
- google-apps-script - 在我不是最后一个发件人的谷歌电子表格中获取电子邮件
- java - 将jOOQ的批处理加载器与onDuplicateKeyUpdate一起使用时,如何仅更新某些字段?
- security - opencti 虚拟机凭据
- python - 在python中将日期(月、日、年、时间)转换为日期时间格式
- spring - 为什么@RestController 默认使用单例范围?
- powershell - 如何使用 Powershell 脚本在远程计算机上查找 PST 文件
- php - 数据表页面就像只有一页一样工作
- angular - 单击铅笔图标编辑内容