Python 循环并更改文件的第一个字母

Python 循环并更改文件的第一个字母,python,os.walk,Python,Os.walk,我在一个文件夹中有大约300个文件,其中第一行是1,我想将其更改为0 这是我用来完成它的一段代码 import os for root,dirs,files in os.walk('/home/decentmakeover2/try/'): for file in files: if file.endswith('.txt'): with open(file, 'r+b') as f: line = next(f) # grab first

我在一个文件夹中有大约300个文件,其中第一行是1,我想将其更改为0

这是我用来完成它的一段代码

import os


for root,dirs,files in os.walk('/home/decentmakeover2/try/'):
for file in files:

    if file.endswith('.txt'):
        with open(file, 'r+b') as f:
            line = next(f) # grab first line
            old = '1'
            new = '0' 
            f.seek(0) 
            f.write(line.replace(old, new))
但是我得到了这个错误

Traceback (most recent call last):
  File "one.py", line 8, in <module>
with open(file, 'r+b') as f:
IOError: [Errno 2] No such file or directory: 'yield_021.txt'
回溯(最近一次呼叫最后一次):
文件“one.py”,第8行,在
打开(文件“r+b”)作为f:
IOError:[Errno 2]没有这样的文件或目录:“yield_021.txt”
但问题是,该文件存在于文件夹中,与其他文件一样,如果我删除该文件,则会出现相同的错误,但文件名不同


有什么想法吗?

使用
os.path.join
,并用文件名连接根目录,因为
open
需要完全限定的路径才能工作

with open(os.path.join(root, file), ...) as f:

其中
root
os.walk

返回的第一个值,请使用
os.path.join
,并使用您的文件名加入您的root,因为
open
需要完全限定的路径才能工作

with open(os.path.join(root, file), ...) as f:

其中
root
是操作系统返回的第一个值。walk

这太完美了!我得再等10分钟才能接受。这太好了!我得再等10分钟才能接受