Python 如果文件不存在则创建
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35807605/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Create a file if it doesn't exist
提问by Miguel Hernandez
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)
. Can I use exist
like in Perl?
错误消息说线路有问题if(!fh)
。我可以exist
在 Perl 中使用like 吗?
回答by Kron
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 Kleinmentioned, 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
回答by Antti Haapala
Well, first of all, in Python there is no !
operator, that'd be not
. But open
would not fail silently either - it would throw an exception. And the blocks need to be indented properly - Python uses whitespace to indicate block containment.
嗯,首先,在 Python 中没有!
运算符,那就是not
. 但open
也不会无声地失败——它会抛出异常。并且块需要正确缩进 - Python 使用空格来表示块包含。
Thus we get:
因此我们得到:
fn = input('Enter file name: ')
try:
file = open(fn, 'r')
except IOError:
file = open(fn, 'w')
回答by Gajendra D Ambi
'''
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 版]
回答by cdarke
Using input()
implies Python 3, recent Python 3 versions have made the IOError
exception deprecated (it is now an alias for OSError
). So assuming you are using Python 3.3 or later:
使用input()
隐含 Python 3,最近的 Python 3 版本已IOError
弃用异常(它现在是 的别名OSError
)。因此,假设您使用的是 Python 3.3 或更高版本:
fn = input('Enter file name: ')
try:
file = open(fn, 'r')
except FileNotFoundError:
file = open(fn, 'w')
回答by That One Random Scrub
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
另外,fh = open ( fh, "w")
当您要打开的文件是fn
回答by Clint Hart
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")
回答by Michael S.
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:. Actually that is the proposed way, according to the python motto "It's easier to ask for forgiveness than permission".
也就是说,您可以按照 That One Random Scrub 的建议进行操作,使用 try: ... except:。实际上,这是建议的方式,根据蟒蛇的座右铭“请求宽恕比许可更容易”。
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. If you accidently want to test for file "import", you'd get a SyntaxError.
注意:使用 raw_input() 而不是 input(),因为 input() 会尝试执行输入的文本。如果您不小心想要测试文件“导入”,您会得到一个 SyntaxError。
回答by psyFi
Here's a quick two-liner that I use to quickly create a file.
这是我用来快速创建文件的快速两行代码。
if not os.path.exists(filename):
open("filename", 'w').close()
`
回答by mahdi babaee
fn = input("Enter file to open: ")
try:
fh = open(fn, "r")
except:
fh = open(fn, "w")