How to create a file in python if it does not exists
我在python中有以下方法。
1 2 3 4 5 6 7 | 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() |
现在在
我试过了,以东十一〔一〕给了我一个例外。
1 2 3 4 5 6 | 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会以写模式创建文件。
在试图写入文件之前,您可以检查
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | 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) |
--编辑:小的,可能不必要的扩展--
扩展用户:在您的例子中,由于最初的问题是用户目录路径中缺少
应用配置目录:由于大多数情况下不希望将文件写入桌面(*nix系统可能没有安装桌面),因此click包中有一个很好的实用程序功能。如果您查看
它应简单如下:
1 2 3 4 | 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"模式可以创建文件。
确保目录存在。