我需要关于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")
错误消息显示,if(!fh)行有问题。我可以像在Perl中那样使用EDOCX1[1]吗?
python中open的可能副本如果不存在,则不会创建文件
首先,在python中没有!操作符,也就是not。但open也不会默默地失败——它会抛出一个例外。而且这些块需要适当地缩进——python使用空白来指示块的包含性。
因此我们得到:
fn = input('Enter file name: ')
try:
file = open(fn, 'r')
except IOError:
file = open(fn, 'w')
我一直在想,为什么这比open(fn, 'a').close()更好。是因为追加中隐含的seek可能太贵了吗?
如果不需要原子性,可以使用OS模块:
import os
if not os.path.exists('/tmp/test'):
os.mknod('/tmp/test')
更新:
正如Cory Klein提到的,在使用os.mknod()的Mac OS上,您需要根权限,因此如果您是Mac OS用户,则可以使用open()而不是os.mknod()。
import os
if not os.path.exists('/tmp/test'):
with open('/tmp/test', 'w'): pass
MacOS需要sudo特权才能运行mknod,所以除非您使用sudo运行python脚本,否则它不太可能移植到Mac。
'''
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
'''
例子:
file_name = 'my_file.txt'
f = open(file_name, 'a+') # open file in append mode
f.write('python rules')
f.close()
我希望这有帮助。[仅供参考,我使用的是Python 3.6.2版]
r+不创建任何文件。正如这里和这里(在描述中)提到的,r+用于以读写模式打开文件。纠正它,因为它可能会使人困惑。)
使用input()意味着python3,最近的python3版本已经使IOError异常被否决(它现在是OSError的别名)。因此,假设您使用的是python 3.3或更高版本:
fn = input('Enter file name: ')
try:
file = open(fn, 'r')
except FileNotFoundError:
file = open(fn, 'w')
我认为这应该有效:
#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')
另外,当您要打开的文件是fn时,您错误地写入了fh = open ( fh,"w")。
您假设文件不存在,因此无法打开。可能是您没有读取权限,或者文件名在某种程度上无效。光秃秃的except不是个好主意。
我明白这一点,(现在)但这对他的编程水平来说已经足够有效了,但我们并不是在教他编程的礼仪,也不是在为class做准备。
好吧,那个可怜的家伙来自Perl,所以他需要他能得到的所有帮助。
这就是我的一天。我们可以解释这些错综复杂的事情,但是,我想睡觉,也许我会在早上向他解释病程,或者你想解释?
警告:每次使用此方法打开文件时,无论是"w+"还是"w",都会销毁文件中的旧数据。
import os
with open("file.txt", 'w+') as f:
f.write("file is opened for business")
密码有错。应该是with open('file.txt', 'w+') as f:。
@通量固定型
fn = input("Enter file to open:")
try:
fh = open(fn,"r")
except:
fh = open(fn,"w")
成功
请试着解释你的答案,使它对其他人更有用。
首先,我要说明的是,您可能不希望创建一个文件对象,该对象最终可以打开进行读或写,这取决于不可复制的条件。您需要知道哪些方法可以使用,读或写,这取决于您想对FileObject做什么。
也就是说,你可以按照一个随机的建议来做,使用try:…除了:事实上,这是提议的方式,根据python的座右铭"请求宽恕比请求允许更容易"。
但你也可以很容易地测试它的存在:
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")
注意:使用原始输入()而不是输入(),因为输入()将尝试执行输入的文本。如果您不小心想要测试文件"import",您将得到一个语法错误。
关于input()和raw_input()的评论只适用于python 2。python 3已经用input()替换了raw_input(),input()的"老"用法已经不复存在了。
这是可能的,而且是一个很好的改进,使它更直观。