繁体   English   中英

如果不存在,如何在python中创建文件

[英]How to create a file in python if it does not exists

我在Python中有以下方法。

def get_rum_data(file_path, query):
    if file_path is not None and query is not None:
        command = FETCH_RUM_COMMAND_DATA % (constants.RUM_JAR_PATH, 
                                            constants.RUM_SERVER, file_path, 
                                            query)
        print command
        execute_command(command).communicate()

现在在get_rum_data内部,如果文件不存在,我需要创建文件,如果存在,则需要附加数据。 如何在python中做到这一点。

我尝试了open(file_path, 'w') ,这给了我一个例外。

Traceback (most recent call last):
  File "utils.py", line 180, in <module>
    get_rum_data('/User/rokumar/Desktop/sample.csv', '\'show tables\'')
  File "utils.py", line 173, in get_rum_data
    open(file_path, 'w')
IOError: [Errno 2] No such file or directory: '/User/rokumar/Desktop/sample.csv'

我虽然打开会在写入模式下创建文件。

它应该很简单:

fname = "/User/rokumar/Desktop/sample.csv"
with open(fname, "a") as f:
    # do here what you want
# it will get closed at this point by context manager

但是我会怀疑,您正在尝试使用不存在的目录。 通常,如果可以创建文件,则“ a”模式将创建文件。

确保目录存在。

您可以在尝试写入文件之前检查file_path所有目录是否都存在。

import os

file_path = '/Users/Foo/Desktop/bar.txt' 
print os.path.dirname(file_path)  
# /Users/Foo/Desktop

if not os.path.exists(os.path.dirname(file_path)):
    os.mkdirs(os.path.dirname(file_path))  
    # recursively create directories if necessary

with open(file_path, "a") as my_file:
    # mode a will either create the file if it does not exist
    # or append the content to its end if it exists.
    my_file.write(your_text_to_append)

-编辑:较小且可能不必要的扩展名-

expanduser:
根据你的情况,因为它变成了,最初的问题是缺少s路径到用户目录,对于解决当前用户的根目录(适用于UNIX,Linux和Windows)一个非常有用的功能:看expanduser从os.path模块。 这样,您可以将路径写为path = '~/Desktop/bar.txt' ,并且波浪符号(〜)会像在shell上一样展开。 (另外的好处是,如果您从其他用户启动脚本,它将扩展到她的主目录。

应用配置目录:
由于在大多数情况下不希望将文件写入桌面(例如,* nix系统可能未安装桌面),因此click包中具有强大的实用程序功能。 如果查看get_app_dir() function on Github上的get_app_dir() function on Github ,则可以看到它们如何提供扩展到适当的应用程序目录并支持多个操作系统的功能(该功能除了_compat.py模块中定义为WIN = sys.platform.startswith('win')WIN变量外,没有任何依赖性。 WIN = sys.platform.startswith('win')和在第17行定义的_posixify()函数。通常,这是定义存储某些数据的应用程序目录的良好起点。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM