Python源文件改写。编写一个 ,读取一个Python源程序文件,将文件中所有除保留字外的小写字母换成大写字母,生成后的文件要能够被 Python 解释器正确执行。
时间: 2024-03-02 10:52:56 浏览: 76
可以使用Python内置的`tokenize`模块来实现这个功能。下面是代码示例:
```python
import keyword
import tokenize
def convert_to_upper(file_in, file_out):
with open(file_in, 'r') as fin:
with open(file_out, 'w') as fout:
for toktype, tok, _, _, _ in tokenize.generate_tokens(fin.readline):
if toktype == tokenize.NAME and not keyword.iskeyword(tok):
tok = tok.upper()
fout.write(tok)
if __name__ == '__main__':
convert_to_upper('example.py', 'example_upper.py')
```
在这个示例中,我们打开一个Python源文件 `example.py`,并使用`tokenize.generate_tokens()`方法来逐行读取文件中的标记(token)。对于每个标记,我们检查它是否是保留字,如果不是,则将其转换为大写字母并写入到输出文件`example_upper.py`中。
需要注意的是,我们需要在写入标记时保留它们之间的空格和换行符,以确保生成的文件能够被Python解释器正确执行。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.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)
![](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://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)