for file_name in os.listdir(dst_folder): if file_name.endswith('.txt'): # 获取文件名(去除后缀) name = os.path.splitext(file_name)[0] with open(os.path.join(dst_folder, file_name), 'r', encoding='gbk') as t: # 将文件名和内容用逗号分隔,并写入列表 file_contents.append(name + ',' + t.read())將這段代碼嗎修改為把文件名按這個代碼寫入filename = os.path.splitext(os.path.basename(file))[0] # 获取文件名(不带后缀) lines = decoded_content.strip().split('\n') for line in lines: merged_text += folder_name + "," + filename + "," + line + "\n"
时间: 2024-01-17 18:05:51 浏览: 35
修改后的代码如下:
```
for file_name in os.listdir(dst_folder):
if file_name.endswith('.txt'):
# 获取文件名(不带后缀)
filename = os.path.splitext(file_name)[0]
with open(os.path.join(dst_folder, file_name), 'r', encoding='gbk') as t:
# 将文件名和内容用逗号分隔,并写入列表
for line in t:
file_contents.append(file_name + ',' + line.strip())
```
修改后的代码将文件名和内容用逗号分隔并存入列表,文件名包括文件后缀。如果需要去掉后缀,可以使用`os.path.splitext(file_name)[0]`来获取不带后缀的文件名。同时,读取文件内容时,可以直接使用`for line in t`来逐行读取文件内容,避免使用`read()`方法一次性读取整个文件内容可能导致内存溢出。
相关问题
代碼報錯,請重新修改import os import shutil from datetime import date # 指定目标文件夹路径和本地路径 src_folder = '目标文件夹路径' dst_folder = '本地路径' # 获取今天的日期 today = date.today() # 遍历目标文件夹中的所有文件 for file_name in os.listdir(src_folder): if file_name.endswith('.txt') and os.path.getmtime(os.path.join(src_folder, file_name)).date() == today: # 如果是今天生成的 txt 文件,复制到本地路径 shutil.copy(os.path.join(src_folder, file_name), os.path.join(dst_folder, file_name)) # 将本地路径中所有 txt 文件的内容汇总到一个文档 with open('汇总文档.txt', 'w') as f: for file_name in os.listdir(dst_folder): if file_name.endswith('.txt'): with open(os.path.join(dst_folder, file_name), 'r') as t: f.write(t.read())
这段代码有一些问题,可能导致代码运行出错。我给你修改一下:
```python
import os
import shutil
from datetime import date
# 指定目标文件夹路径和本地路径
src_folder = '目标文件夹路径'
dst_folder = '本地路径'
# 获取今天的日期
today = date.today()
# 遍历目标文件夹中的所有文件
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:
# 如果是今天生成的 txt 文件,复制到本地路径
shutil.copy(file_path, os.path.join(dst_folder, file_name))
# 将本地路径中所有 txt 文件的内容汇总到一个文档
with open('汇总文档.txt', 'w') as f:
for file_name in os.listdir(dst_folder):
if file_name.endswith('.txt'):
with open(os.path.join(dst_folder, file_name), 'r') as t:
f.write(t.read())
```
主要修改如下:
1. 在检查文件是否是今天生成的时,使用 `date.fromtimestamp` 方法将文件的修改时间转换为日期格式。
2. 在处理文件路径时,使用 `os.path.join` 方法拼接路径,避免路径拼接不正确的问题。
代碼報錯,請修改import os import shutil from datetime import date src_folder = r"Y:\iplas\Robot_Log\SMT" dst_folder = "D:\測試log" today = date.today() 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: shutil.copy(file_path, os.path.join(dst_folder, f"{file_name},{file_name}")) file_contents = [] for file_name in os.listdir(dst_folder): if file_name.endswith('.txt'): 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}") with open(os.path.join(dst_folder, '汇总文档.txt'), 'w', encoding='gbk') as f: f.write('\n\n'.join(file_contents))
请尝试使用以下代码,它会在文件名中添加当天日期,并且在复制文件时会创建目标文件夹(如果不存在),还会在文件读取时处理异常情况:
```
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)
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))
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\n'.join(file_contents))
```
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![xlsx](https://img-home.csdnimg.cn/images/20210720083732.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)