简体   繁体   English

如果文件不存在则创建

[英]Create a file if it doesn't exist

I'm trying to open a file, and if the file doesn't exist, I need to create it and open it for writing.我正在尝试打开一个文件,如果该文件不存在,我需要创建它并打开它进行写入。 I have this so far:到目前为止我有这个:

#open file for reading
fn = input("Enter file to open: ")
fh = open(fn,'r')
# if file does not exist, create it
if (!fh) 
fh = open ( fh, "w")

The error message says there's an issue on the line if(!fh) .错误消息表明if(!fh)线路存在问题。 Can I use exist like in Perl?我可以像 Perl 一样使用exist吗?

If you don't need atomicity you can use os module:如果你不需要原子性,你可以使用 os 模块:

import os

if not os.path.exists('/tmp/test'):
    os.mknod('/tmp/test')

UPDATE :更新

As Cory Klein mentioned, on Mac OS for using os.mknod() you need a root permissions, so if you are Mac OS user, you may use open() instead of os.mknod()正如Cory Klein提到的,在 Mac OS 上使用os.mknod()你需要一个 root 权限,所以如果你是 Mac OS 用户,你可以使用open()而不是os.mknod()

import os

if not os.path.exists('/tmp/test'):
    with open('/tmp/test', 'w'): pass
'''
w  write mode
r  read mode
a  append mode

w+  create file if it doesn't exist and open it in (over)write mode
    [it overwrites the file if it already exists]
r+  open an existing file in read+write mode
a+  create file if it doesn't exist and open it in append mode
'''

example:例子:

file_name = 'my_file.txt'
f = open(file_name, 'a+')  # open file in append mode
f.write('python rules')
f.close()

I hope this helps.我希望这有帮助。 [FYI am using python version 3.6.2] [仅供参考,我使用的是 Python 3.6.2 版]

Well, first of all, in Python there is no !好吧,首先,在 Python 中没有! operator, that'd be not .运营商,那not But open would not fail silently either - it would throw an exception.但是open也不会无声地失败——它会抛出异常。 And the blocks need to be indented properly - Python uses whitespace to indicate block containment.并且块需要正确缩进 - Python 使用空格来表示块包含。

Thus we get:因此我们得到:

fn = input('Enter file name: ')
try:
    file = open(fn, 'r')
except IOError:
    file = open(fn, 'w')

Here's a quick two-liner that I use to quickly create a file if it doesn't exists.这是一个快速的两行代码,如果文件不存在,我会用它来快速创建一个文件。

if not os.path.exists(filename):
    open(filename, 'w').close()

Using input() implies Python 3, recent Python 3 versions have made the IOError exception deprecated (it is now an alias for OSError ).使用input()意味着 Python 3,最近的 Python 3 版本已经弃用了IOError异常(它现在是OSError的别名)。 So assuming you are using Python 3.3 or later:因此,假设您使用的是 Python 3.3 或更高版本:

fn = input('Enter file name: ')
try:
    file = open(fn, 'r')
except FileNotFoundError:
    file = open(fn, 'w')

I think this should work:我认为这应该有效:

#open file for reading
fn = input("Enter file to open: ")
try:
    fh = open(fn,'r')
except:
# if file does not exist, create it
    fh = open(fn,'w')

Also, you incorrectly wrote fh = open ( fh, "w") when the file you wanted open was fn另外,当您要打开的文件是fn时,您错误地写了fh = open ( fh, "w")

Be warned, each time the file is opened with this method the old data in the file is destroyed regardless of 'w+' or just 'w'.请注意,每次使用此方法打开文件时,文件中的旧数据都会被破坏,无论是“w+”还是“w”。

import os

with open("file.txt", 'w+') as f:
    f.write("file is opened for business")

First let me mention that you probably don't want to create a file object that eventually can be opened for reading OR writing, depending on a non-reproducible condition.首先让我提一下,您可能不想创建一个最终可以打开以进行读取或写入的文件对象,具体取决于不可重现的条件。 You need to know which methods can be used, reading or writing, which depends on what you want to do with the fileobject.您需要知道可以使用哪些方法,读或写,这取决于您想对文件对象做什么。

That said, you can do it as That One Random Scrub proposed, using try: ... except:.也就是说,您可以按照 That One Random Scrub 的建议进行操作,使用 try: ... except:。 Actually that is the proposed way, according to the python motto "It's easier to ask for forgiveness than permission".实际上,这是建议的方式,根据蟒蛇的座右铭“请求宽恕比许可更容易”。

But you can also easily test for existence:但是您也可以轻松测试是否存在:

import os
# open file for reading
fn = raw_input("Enter file to open: ")
if os.path.exists(fn):
    fh = open(fn, "r")
else:
    fh = open(fn, "w")

Note: use raw_input() instead of input(), because input() will try to execute the entered text.注意:使用 raw_input() 而不是 input(),因为 input() 会尝试执行输入的文本。 If you accidently want to test for file "import", you'd get a SyntaxError.如果您不小心想要测试文件“导入”,您会得到一个 SyntaxError。

If you know the folder location and the filename is the only unknown thing,如果您知道文件夹位置和文件名是唯一未知的东西,

open(f"{path_to_the_file}/{file_name}", "w+")

if the folder location is also unknown如果文件夹位置也是未知的

try using尝试使用

pathlib.Path.mkdir
fn = input("Enter file to open: ")
try:
    fh = open(fn, "r")
except:
    fh = open(fn, "w")

success 成功

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

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