python中将几列txt文件写入mysql该怎么写
时间: 2023-06-06 07:04:57 浏览: 82
可以通过Python的MySQLdb库实现将txt文件写入MySQL的操作,下面是一个简单的示例代码:
```python
import MySQLdb
# 连接MySQL数据库
db = MySQLdb.connect(host="localhost", user="username", passwd="password", db="database_name", charset="utf8")
cursor = db.cursor()
# 读取txt文件
with open('data.txt', 'r') as f:
lines = f.readlines()
# 将数据插入MySQL表中
for line in lines:
data = line.strip().split(',')
sql = "INSERT INTO table_name(col1, col2, col3) VALUES ('%s', '%s', '%s')" % (data[0], data[1], data[2])
cursor.execute(sql)
db.commit()
# 关闭数据库连接
db.close()
```
这段代码假设txt文件中每行数据由三个字段组成,用逗号隔开,插入到MySQL表的三列分别为col1、col2、col3。具体根据自己的需求修改代码。
相关问题
python 批量向txt文件写入内容 endswith
Python 中可以使用 `endswith()` 方法来判断字符串是否以指定后缀结尾。要批量向多个 txt 文件写入内容并检查文件名是否以特定后缀结尾,可以按照以下步骤进行操作:
1. 首先,需要导入 `os` 模块来处理文件操作,例如判断文件是否存在等。
2. 创建一个包含所有待处理文件名的列表。
3. 使用 `for` 循环遍历文件列表。
4. 在循环中,使用 `endswith()` 方法检查文件名是否以特定的后缀结尾。
5. 如果文件名以指定的后缀结尾,则使用文件路径和文件名打开文件,并以追加模式(`'a'`)写入内容,如果文件不存在则自动创建。
下面是一个示例代码:
```python
import os
files = ["file1.txt", "file2.txt", "file3.txt"]
suffix = ".txt"
content = "Hello, world!"
for file in files:
if file.endswith(suffix):
with open(file, "a") as f:
f.write(content + "\n")
print(f"已向文件 {file} 写入内容")
else:
print(f"文件 {file} 不是以 {suffix} 结尾")
```
以上代码会将字符串 "Hello, world!" 写入以 `.txt` 后缀结尾的文件中,并在控制台输出相应的提示信息。
请注意,以上示例是简化的代码,实际使用中可能需要添加一些异常处理逻辑,如检查文件是否存在、处理文件路径,等等。
python中将列表写入文件
以下是两种将列表写入文件的方法:
方法一:使用文件操作符将列表写入txt文件中
```python
a=[['1','9'],['2','5'],['3','3'],['2','4'],['4','3'],['1','8'],['1','9']]
t=''
with open ('N_a.txt','w') as q:
for i in a:
for e in range(len(a[0])):
t=t+str(i[e])+' '
q.write(t.strip(' '))
q.write('\n')
t=''
```
方法二:使用text_save函数将列表写入txt文件中
```python
# 将操作码保存为txt文件
def text_save(filename, data):
# filename为写入txt文件的路径,data为要写入数据列表.
file = open(filename, 'a')
for i in range(len(data)):
s = str(data[i]).replace('[', '').replace(']', '')#去除[],这两行按数据不同,可以选择
s = s.replace("'", '').replace(',', '') + '\n' #去除单引号,逗号,每行末尾追加换行符
file.write(s)
file.close()
print("保存文件成功")
ops = [['i','love','china'],['happy','birthday']]
text_save('ops.txt', ops)
```