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

时间:2015-01-06 11:06:38

标签: 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会在写模式下创建文件。

2 个答案:

答案 0 :(得分:1)

应该如此简单:

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”模式会创建文件。

确保目录存在。

答案 1 :(得分:1)

在尝试编写文件之前,您可以检查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):请参阅os.path模块中的expanduser。有了这个,您可以将路径写为path = '~/Desktop/bar.txt',并且波形符(〜)将像在shell上一样展开。 (另外一个好处是,如果你从另一个用户启动你的脚本,它将扩展到她的主目录。

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