我是一个新的Python3,所以请给我问这个问题的答案,但是我在Google上找不到答案,我已经扫描了一个文件目录,我需要在结果中添加一个开放的、接近的括号和一个新的var,这样我就可以将它插入数据库中。
Mysql需要将插入封装在val =('test.mp4',newip) 中的括号中--这是在运行硬编码脚本时插入的1。
因此,我试图归档的是修改扫描结果,并在扫描结果中添加以下打开/关闭括号和新的newip,如下所示
扫描结果
'test.mp4','test_2.mp4','test_3.mp4',test_4.mp4'‘
插入新结果(修改)
('test',newip),('test_2.mp4',newip),('test_3.mp4',newip),('test_4.mp4',newip)
当硬编码它的作品
root@ubuntu:~# python3 testscan.py
['test.mp4', 'test_2.mp4', 'test_3.mp4', test_4.mp4']
1 was inserted.请任何人建议如何做到这一点,下面是完整的代码。
import os, mysql.connector, re, uuid
files = [f.name for f in (os.scandir('/var/www/html/media/usb1')) if f.name.endswith('.mp4')]
print(files)
newip = (':'.join(re.findall('..', '%012x' % uuid.getnode())))
mydb = mysql.connector.connect(
host="127.0.0.1",
user="user",
password="password",
database="database"
)
mycursor = mydb.cursor()
sql = "INSERT IGNORE INTO files (file,ip) VALUES (%s,%s)"
val =[('test.mp4',newip)]
mycursor.executemany(sql, val)
mydb.commit()
print(mycursor.rowcount, "was inserted.")发布于 2020-08-06 09:57:13
因此,如果要将newip添加到扫描中,可以使用列表理解:
files = ['test.mp4', 'test_2.mp4', 'test_3.mp4', 'test_4.mp4']
sql_values = [(file, newip) for file in files]结果如下:
[('test.mp4', newip), ('test2.mp4', newip), ('test3.mp4', newip), ('test4.mp4', newip)]https://stackoverflow.com/questions/63280802
复制相似问题