2016-05-23 83 views
-1

我是Python的新手,并且希望在根文件夹中的所有文件的每行(仅在指定的文件扩展名中)和所有带有Python脚本的子文件夹中添加文本行。 我从互联网上收集哪些:在文件夹的每个文件的每一行后面写入字符串

import os 
import fnmatch 

for root, dirs, files in os.walk("dir"): 
    for filename in files: 
     if filename.endswith(".x",".y"): 
      with open(filename, "r") as f: 
       file_lines = [''.join([x.strip(), "some_string", '\n']) for x in f.readlines()] 
      with open(filename, "w") as f: 
       f.writelines(file_lines) 

我有一个小文件夹测试,但得到的错误: IO错误:[错误2]没有这样的文件或目录

回答

0

公开赛在append模式下的文件。

码 -

import os 


def foo(root, desired_extensions, text_line): 
    for subdir, dirs, files in os.walk(root): 
     for f in files: 
      file_path = os.path.join(subdir, f) 
      file_extension = os.path.splitext(file_path)[1] 
      if file_extension in desired_extensions: 
       with open(file_path, 'a') as f: 
        f.write(text_line + '\n') 


if __name__ == '__main__': 
    foo('/a/b/c/d', {'.txt', '.cpp'}, 'blahblahblah') 
0

的问题是,你试图仅仅通过它的名称来访问文件 - 忽略了其位置路径。 您需要使用完整路径才能访问文件:os.path.join(root,filename)

0

filename不包括路径。您需要自行创建完整路径,方法是加入rootfilename。我会建议如下:

for path, _, files in os.walk("dir"): 
    for filename in files: 
     if os.path.splitext(filename)[1] in ("x", "y"): 
      with open(os.path.join(path, filename)) as file: 
       file_lines = ... 
      ... 
相关问题