2017-10-18 69 views
0

我具有其中第一行是1的文件夹中大约300个文件,我想将其改为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' 

但事情是该文件存在的文件夹,并且它只是像其他文件,如果我删除的文件,然后我得到相同的错误,但具有不同的文件名称

有什么想法?

回答

2

使用os.path.join,并加入您的根与您的文件名,因为open需要完全合格的路径工作。

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

rootos.walk返回第一个值。

+0

这是完美! – Ryan

+0

我必须等10分钟才能接受它 – Ryan

+0

@瑞安没问题,不客气。 –

相关问题