首页 > 解决方案 > 如何读取 .py 文件并向其中添加代码?

问题描述

我正在尝试.py读取python 3.6. 目的是在不手动浏览所有文件和编辑代码的情况下替换/添加一些代码。

import os

py_files = []
for path, subdirs, files in os.walk(location):
    for name in files:
        if '.py' in name:
            py_files.append(os.path.join(path, name))

test_file = py_file[0]
t = open(test_file,'r').read()  # Trying a read only to check whether I can see the text
print(t)

# assuming this starts working.
#I want to see the file and then use a .replace and save the file. 
#I assume saving it back as `.py` might present a challenge

我得到的输出是''.

不知道如何完成这项工作。

标签: python

解决方案


推荐阅读