I need help with Python. 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:
我需要Python的帮助。我正在尝试打开一个文件,如果该文件不存在,我需要创建它并打开它进行写入。到目前为止我有这个:
#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?
错误消息表示如果(!fh)行上有问题。我可以像Perl一样使用存在吗?
7 个解决方案
#1
25
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中没有!运营商,那不是。但open也不会默默地失败 - 它会引发异常。并且块需要正确缩进 - Python使用空格来指示块包含。
Thus we get:
因此我们得到:
fn = input('Enter file name: ')
try:
file = open(fn, 'r')
except IOError:
file = open(fn, 'w')
#2
18
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
#3
8
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')
#4
7
'''
w write mode
r read mode
a append mode
w+ create file if it doesn't exist and open it in write mode
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版]
#5
4
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”)
#6
0
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".
也就是说,你可以做那个随机磨砂提议,使用try:...除了:实际上这是建议的方式,根据蟒蛇的座右铭“要求宽恕比允许更容易”。
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()将尝试执行输入的文本。如果你意外地想要测试文件“import”,你会得到一个SyntaxError。
#7
0
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")
#1
25
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中没有!运营商,那不是。但open也不会默默地失败 - 它会引发异常。并且块需要正确缩进 - Python使用空格来指示块包含。
Thus we get:
因此我们得到:
fn = input('Enter file name: ')
try:
file = open(fn, 'r')
except IOError:
file = open(fn, 'w')
#2
18
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
#3
8
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')
#4
7
'''
w write mode
r read mode
a append mode
w+ create file if it doesn't exist and open it in write mode
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版]
#5
4
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”)
#6
0
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".
也就是说,你可以做那个随机磨砂提议,使用try:...除了:实际上这是建议的方式,根据蟒蛇的座右铭“要求宽恕比允许更容易”。
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()将尝试执行输入的文本。如果你意外地想要测试文件“import”,你会得到一个SyntaxError。
#7
0
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")