Python循环将单个文件内容追加到多份README.md仅首次生效如何解决
问题原因
你仅在脚本初始化时打开了一次append.md文件对象,第一次执行appendFile.read()操作后,文件读取指针已经移动到了append.md的文件末尾,后续遍历到其他README.md再调用read()方法时,只能读取到空内容,所以后续的追加操作看起来没有生效,这个问题和flush、fsync操作无关。
修复方案
方案1(推荐):提前加载追加内容到内存
如果append.md文件体积不大,优先选择提前将内容读取为字符串复用,性能最好,也不会出现指针偏移问题。
import os # 提前读取待追加的内容,仅读取一次 with open('./append.md', 'r', encoding='utf-8') as f: append_content = f.read() for project, dirs, filenames in os.walk('.'): # 跳过根目录 if project == '.': continue # 直接判断当前目录是否存在README.md,无需遍历所有文件 if 'README.md' in filenames: readme_path = os.path.join(project, 'README.md') print(f'Current Project is {project}.') print(f'Current README is {readme_path}.') with open(readme_path, 'a', encoding='utf-8') as readme_f: readme_f.write(append_content)
方案2:重置文件指针
如果append.md体积很大,不想一次性加载到内存,可以每次写入前将append.md的读取指针重置到文件开头:
import os appendFile = open('./append.md', 'r', encoding='utf-8') for project, dirs, filenames in os.walk('.'): if project == '.': continue if 'README.md' in filenames: readme_path = os.path.join(project, 'README.md') print(f'Current Project is {project}.') print(f'Current README is {readme_path}.') with open(readme_path, 'a', encoding='utf-8') as readme_f: # 重置指针到文件起始位置 appendFile.seek(0) readme_f.write(appendFile.read()) appendFile.close()
注意:代码中显式指定了
encoding='utf-8',可以避免不同操作系统默认编码不一致导致的乱码问题。
内容的提问来源于stack exchange,提问作者notmyidea
相关产品推荐
相关产品推荐

