請你寫完整代碼我需要寫入的表名稱不是在每個内容的最後面,我需要卸載每個内容相應加載每行後面import os import shutil from datetime import date src_folder = r"Y:\iplas\Robot_Log\SMT" dst_folder = r"D:\測試log" today = date.today() # create target folder if it does not exist if not os.path.exists(dst_folder): os.makedirs(dst_folder) # copy files and rename for file_name in os.listdir(src_folder): if file_name.endswith('.txt'): file_path = os.path.join(src_folder, file_name) if date.fromtimestamp(os.path.getmtime(file_path)) == today: new_file_name = f"{file_name[:-4]}_{today.strftime('%Y%m%d')}.txt" shutil.copy(file_path, os.path.join(dst_folder, new_file_name)) # write file contents with corresponding file names file_contents = [] for file_name in os.listdir(dst_folder): if file_name.endswith('.txt'): try: with open(os.path.join(dst_folder, file_name), 'r', encoding='gbk') as t: file_content = t.read().strip() file_contents.append(f"{file_content},{file_name}") except Exception as e: print(f"Error reading file {file_name}: {e}") with open(os.path.join(dst_folder, '汇总文档.txt'), 'w', encoding='gbk') as f: f.write('\n'.join(file_contents))
时间: 2023-12-12 09:04:33 浏览: 102
抱歉,我无法提供完整代码,因为我不知道你要写入的表名是什么,而且你也没有提供任何关于数据库的信息。但是,我可以给你一些提示来帮助你完成代码:
1. 首先,你需要连接到数据库,并且创建一个游标对象。
2. 然后,你需要处理每个文件并将其内容写入数据库中。你可以使用类似下面的代码:
```python
import pymysql
# Connect to the database
conn = pymysql.connect(host='localhost', user='root', password='password', db='mydb')
cursor = conn.cursor()
# Process each file and write its content to the database
for file_name in os.listdir(dst_folder):
if file_name.endswith('.txt'):
try:
with open(os.path.join(dst_folder, file_name), 'r', encoding='gbk') as t:
file_content = t.read().strip()
table_name = # The table name you want to write the content to
query = f"INSERT INTO {table_name} (content, file_name) VALUES ('{file_content}', '{file_name}')"
cursor.execute(query)
conn.commit()
except Exception as e:
print(f"Error reading file {file_name}: {e}")
# Close the cursor and connection
cursor.close()
conn.close()
```
3. 最后,你可以在数据库中查询相应的表来确认数据是否被成功写入。
请注意,这只是一个大致的框架,你需要根据自己的具体情况进行适当的修改。
阅读全文