【问题标题】:Creating files in specific path with python使用python在特定路径中创建文件
【发布时间】:2020-08-10 14:34:57
【问题描述】:

是否可以使用 sys 模块或任何其他模块创建具有特定扩展名、名称和 python 的文件?

谢谢!

【问题讨论】:

    标签: python file path new-operator sys


    【解决方案1】:

    使用

    f = open('myfile.myextension', 'w')
    f.write('hello')
    f.close()
    

    您可以创建具有您想要的任何扩展名的文件。如果您想要其他软件读取它,例如,如果您想要创建一个 excel 文件 (xlsx) 或 pdf,您可能需要额外的软件包。

    【讨论】:

    • 并在末尾添加f.close(),以免崩溃。
    【解决方案2】:

    这应该与路径和文件名一起使用:

    import os
    
    PATH = '/home/user/somepath'
    FILE = 'somefile.someext'
    
    os.makedirs( PATH, exist_ok=True)   # create the PATH if not exists
    
    full_name = os.path.join( PATH, FILE )
    with open( full_name ) as fout :
        print >>fout, 'some message'
    

    【讨论】:

      猜你喜欢
      • 2020-04-30
      • 2021-07-06
      • 2019-05-17
      • 2013-05-13
      • 1970-01-01
      • 2019-12-28
      • 2020-09-20
      • 2014-12-11
      • 2020-05-14
      相关资源
      最近更新 更多