【问题标题】:how to open a gz file and save the file as txt in python如何在python中打开gz文件并将文件另存为txt
【发布时间】:2018-11-15 03:09:07
【问题描述】:

我有一个gz文件,如何解压文件并将内容保存到python中的txt? 我已经导入了 gzip

file_path = gzip.open(file_name, 'rb')

【问题讨论】:

  • 您是否尝试过查看该对象现在可以使用哪些功能?

标签: python io gzip


【解决方案1】:

如何打开第二个文件并写入它?

import gzip
with gzip.open('file.txt.gz', 'rb') as f, open('file.txt', 'w') as f_out:
    f_out.write(f.read())

【讨论】:

    【解决方案2】:

    Gzip 的 open 方法应该打开文件,使其内容可以像普通文件一样被读取:

    import gzip
    
    #Define the file's location
    file_path = "/path/to/file.gz"
    
    #Open the file and read its contents
    with gzip.open(file_path, "rb") as file:
        file_content = file.read()
    
    
    #Save the new txt file
    txt_file_name = "txtFile.txt"
    
    with open(txt_file_name, "w") as file:
        file.write(file_content)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-24
      • 2017-05-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-07
      • 2019-07-01
      相关资源
      最近更新 更多