Mig*_*dez 46 python createfile
我需要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")
Run Code Online (Sandbox Code Playgroud)
错误消息表明该行存在问题if(!fh)
.我可以exist
在Perl中使用吗?
Kro*_*ron 37
如果您不需要原子性,可以使用os模块:
import os
if not os.path.exists('/tmp/test'):
os.mknod('/tmp/test')
Run Code Online (Sandbox Code Playgroud)
更新:
正如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
Run Code Online (Sandbox Code Playgroud)
Ant*_*ala 33
好吧,首先,在Python中没有!
运算符,那就是not
.但是open
也不会默默地失败 - 它会引发异常.并且块需要正确缩进 - Python使用空格来指示块包含.
因此我们得到:
fn = input('Enter file name: ')
try:
file = open(fn, 'r')
except IOError:
file = open(fn, 'w')
Run Code Online (Sandbox Code Playgroud)
Gaj*_*mbi 23
'''
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
'''
Run Code Online (Sandbox Code Playgroud)
例:
file_name = 'my_file.txt'
f = open(file_name, 'a+') # open file in append mode
f.write('python rules')
f.close()
Run Code Online (Sandbox Code Playgroud)
我希望这有帮助.[仅供参考使用python 3.6.2版]
psy*_*yFi 23
这是一个快速的两行代码,如果文件不存在,我会用它来快速创建一个文件。
if not os.path.exists(filename):
open(filename, 'w').close()
Run Code Online (Sandbox Code Playgroud)
cda*_*rke 10
使用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')
Run Code Online (Sandbox Code Playgroud)
小智 7
请注意,每次使用此方法打开文件时,文件中的旧数据都会被破坏,'w+'
无论'w'
.
with open("file.txt", 'w+') as f:
f.write("file is opened for business")
Run Code Online (Sandbox Code Playgroud)
我认为这应该工作:
#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')
Run Code Online (Sandbox Code Playgroud)
另外,fh = open ( fh, "w")
当您要打开的文件是fn
归档时间: |
|
查看次数: |
160671 次 |
最近记录: |