如何在python中创建不存在的文件

2024-05-12 18:51:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我在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'

我想open会以写模式创建文件。


Tags: 文件pathnonedatagetisnotopen
2条回答

应简单如下:

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)

--Edit:扩展很小,可能不必要--

扩展用户:
在您的案例中,由于最初的问题是用户目录路径中缺少s,因此有一个有用的功能可用于解决当前用户基本目录(适用于unix、linux和windows):请参见os.path模块中的expanduser。有了它,您可以将路径写为path = '~/Desktop/bar.txt',波浪号(~)将像在shell上一样展开。(另一个好处是,如果您从另一个用户启动脚本,它将扩展到她的主目录。

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

相关问题 更多 >