用python读取python源程序文件并改写文件
时间: 2024-05-29 12:05:10 浏览: 16
可以使用Python内置的文件操作函数来读取和修改Python源程序文件。具体步骤如下:
1. 打开源程序文件,使用`open()`函数,指定文件路径和打开模式,例如:
```python
with open('source.py', 'r') as f:
source_code = f.read()
```
这里使用了`with`语句,可以自动关闭文件。
2. 修改源程序文件,例如将所有的`print`语句改为`logging`语句:
```python
import ast
class PrintToLogging(ast.NodeTransformer):
def visit_Call(self, node):
if isinstance(node.func, ast.Name) and node.func.id == 'print':
node.func.id = 'logging.info'
return node
tree = ast.parse(source_code)
new_tree = PrintToLogging().visit(tree)
new_source_code = ast.unparse(new_tree)
```
这里使用了`ast`模块,将源程序代码解析成抽象语法树,然后使用`NodeTransformer`类来修改语法树,最后将修改后的语法树重新转换成源程序代码。
3. 将修改后的源程序代码写入文件,使用`open()`函数,指定文件路径和打开模式,例如:
```python
with open('new_source.py', 'w') as f:
f.write(new_source_code)
```
完整代码如下:
```python
import ast
import logging
with open('source.py', 'r') as f:
source_code = f.read()
class PrintToLogging(ast.NodeTransformer):
def visit_Call(self, node):
if isinstance(node.func, ast.Name) and node.func.id == 'print':
node.func.id = 'logging.info'
return node
tree = ast.parse(source_code)
new_tree = PrintToLogging().visit(tree)
new_source_code = ast.unparse(new_tree)
with open('new_source.py', 'w') as f:
f.write(new_source_code)
```
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)