import os # 获取文件夹路径 folder_path = 'label' folder_path1 = 'new' # 获取文件夹中的所有txt文件 files = [f for f in os.listdir(folder_path) if f.endswith('.txt')] # 遍历所有txt文件 for filename in files: file_path = os.path.join(folder_path, filename) filename=filename[7:13] id='' for c in filename: if c.isdigit(): id += c if len(id)<6: id = int(id) filename = str(id) file_path = os.path.join(folder_path, filename) with open(filename, 'r', encoding='utf-8') as file: content = file.read() # 替换第一个字符串 content = content.replace(content.split()[0], str(start_num)) # 写入修改后的内容 new_filename = filename.replace('.txt', '.txt') new_file_path = os.path.join(folder_path1, new_filename) with open(new_file_path, 'w', encoding='utf-8') as new_file: new_file.write(content) start_num = 0 increment = 1 # 更新起始数值 if id % 3 == 0: start_num += increment为什么找不到文件了,有什么办法解决
时间: 2023-12-13 20:05:23 浏览: 175
New folder (3).zip_What Is the What_code_new folder 3
根据你提供的代码,找不到文件的问题可能是因为文件路径没有正确设置。具体来说,你在打开文件时使用了`filename`作为文件路径,但是`filename`在此之前已经被修改为一个数字或字符串,而不是完整的文件路径。
为了解决这个问题,你可以使用`file_path`变量来打开文件和写入修改后的内容。将以下代码段:
```
with open(filename, 'r', encoding='utf-8') as file:
content = file.read()
```
替换为:
```
with open(file_path, 'r', encoding='utf-8') as file:
content = file.read()
```
同样地,将以下代码段:
```
new_filename = filename.replace('.txt', '.txt')
new_file_path = os.path.join(folder_path1, new_filename)
with open(new_file_path, 'w', encoding='utf-8') as new_file:
new_file.write(content)
```
替换为:
```
new_filename = filename.replace('.txt', '.txt')
new_file_path = os.path.join(folder_path1, new_filename)
with open(os.path.join(folder_path1, new_file_path), 'w', encoding='utf-8') as new_file:
new_file.write(content)
```
这样修改后,文件路径应该被正确地设置,可以找到并操作文件。如果问题仍然存在,请提供更多错误信息以便进一步排查。
阅读全文