python脚本压缩txt文件
时间: 2023-07-29 20:11:04 浏览: 282
你可以使用Python内置的gzip模块来压缩txt文件。下面是一个简单的示例代码:
```python
import gzip
def compress_txt_file(input_file_path, output_file_path):
with open(input_file_path, 'rb') as input_file:
with gzip.open(output_file_path, 'wb') as output_file:
output_file.writelines(input_file)
input_file_path = 'input.txt'
output_file_path = 'compressed.txt.gz'
compress_txt_file(input_file_path, output_file_path)
```
在上面的代码中,`compress_txt_file`函数接受输入文件路径和输出文件路径作为参数。它使用`open`函数打开输入文件并以二进制模式读取内容,然后使用`gzip.open`函数以二进制模式打开输出文件并将输入文件的内容写入其中。
你需要将`input.txt`替换为你要压缩的txt文件的路径,并指定一个输出文件路径,例如`compressed.txt.gz`。压缩后的文件将以gzip格式保存。
请确保在运行代码之前已经安装了Python的gzip模块。你可以使用以下命令安装它:
```
pip install gzip
```
希望这可以帮助到你!
阅读全文
相关推荐















