import os # 获取data文件夹的路径 data_folder = 'D:/PythonProject/jicheng/data_1' # 遍历data文件夹中的所有txt文件 for filename in sorted(os.listdir(data_folder)): if filename.endswith('.txt'): # 获取txt文件的名称所对应的整数 file_num = int(filename.split('.')[0]) # 打开txt文件并读取每一行 with open(os.path.join(data_folder, filename), 'r') as f: lines = f.readlines() # 将每一行最前面加上所对应的整数 lines = [str(file_num) + line for line in lines] # 将处理后的txt文件保存 with open(os.path.join(data_folder, filename), 'w') as f: f.writelines(lines) # 将所有txt文件按照命名顺序整合至一个文本文件 with open(os.path.join(data_folder, '0001.txt'), 'w') as f: for filename in sorted(os.listdir(data_folder)): if filename.endswith('.txt'): with open(os.path.join(data_folder, filename), 'r') as f2: f.write(f2.read())该脚本文件出现了往0001.txt文件中整合过多文件的错误,例如data_1中只有0到313个文件,则整合后的0001.txt中的每一行最前面的数应该为0到313,可是却多出现了重复的内容,0001.txt中先出现了0-199号文件的内容,再从0开始出现0-313号文件的内容,你知道这是为什么吗。我该如何修改代码以解决这个错误,请给我详细代码
时间: 2024-03-10 16:46:54 浏览: 31
出现这个错误的原因是代码将所有的txt文件都按照文件名排序后整合到了一个文件中,但是文件名中的数字并不一定是按照顺序排列的,例如文件名为'10.txt'的文件会排在文件名为'9.txt'的文件之后。因此,在整合文件时需要按照文件名中的数字进行排序。
修改代码如下:
```python
import os
data_folder = 'D:/PythonProject/jicheng/data_1'
# 获取data文件夹中所有的txt文件
txt_files = []
for filename in os.listdir(data_folder):
if filename.endswith('.txt'):
txt_files.append(filename)
# 按照文件名中的数字进行排序
txt_files = sorted(txt_files, key=lambda x: int(x.split('.')[0]))
# 遍历所有的txt文件,将每个文件的内容按照要求处理后,写入到0001.txt文件中
with open(os.path.join(data_folder, '0001.txt'), 'w') as f:
for filename in txt_files:
file_num = int(filename.split('.')[0])
with open(os.path.join(data_folder, filename), 'r') as f2:
lines = f2.readlines()
lines = [str(file_num) + line for line in lines]
f.writelines(lines)
```
修改后的代码首先获取所有的txt文件,并按照文件名中的数字进行排序。然后遍历所有的txt文件,将每个文件的内容按照要求处理后,写入到0001.txt文件中。这样就能够避免出现重复的内容了。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)
![](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)
![7z](https://img-home.csdnimg.cn/images/20210720083312.png)