python文件不存在时创建文件_python-创建一个文件(如果不存在)
python-創建一個文件(如果不存在)
我需要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中一樣使用exist嗎?
8個解決方案
35 votes
如果您不需要原子性,則可以使用os模塊:
import os
if not os.path.exists('/tmp/test'):
os.mknod('/tmp/test')
更新:
正如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
Kron answered 2020-07-23T16:06:46Z
32 votes
好吧,首先,在Python中沒有!運算符,即not。但是open也不會默默地失敗-它將引發異常。 并且需要適當地縮進塊-Python使用空格指示塊包含。
這樣我們得到:
fn = input('Enter file name: ')
try:
file = open(fn, 'r')
except IOError:
file = open(fn, 'w')
Antti Haapala answered 2020-07-23T16:07:11Z
20 votes
'''
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
'''
例:
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版]
Gajendra D Ambi answered 2020-07-23T16:07:35Z
10 votes
使用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')
cdarke answered 2020-07-23T16:07:55Z
6 votes
我認為這應該工作:
#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")
That One Random Scrub answered 2020-07-23T16:08:22Z
1 votes
請注意,每次使用此方法打開文件時,文件中的舊數據都會被破壞,無論'w +'還是只是'w'。
import os
with open("file.txt", 'w+') as f:
f.write("file is opened for business")
Clint Hart answered 2020-07-23T16:08:42Z
0 votes
首先讓我提到,您可能不希望創建一個文件對象,該文件對象最終可以打開以進行讀取或寫入,這取決于不可復制的條件。 您需要知道可以使用,讀取或寫入哪些方法,這取決于您要對文件對象執行的操作。
也就是說,您可以使用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")
注意:請使用raw_input()而不是input(),因為input()會嘗試執行輸入的文本。 如果您不小心要測試文件“導入”,則會收到SyntaxError。
Michael S. answered 2020-07-23T16:09:16Z
-2 votes
fn = input("Enter file to open: ")
try:
fh = open(fn, "r")
except:
fh = open(fn, "w")
成功
mahdi babaee answered 2020-07-23T16:09:36Z
總結
以上是生活随笔為你收集整理的python文件不存在时创建文件_python-创建一个文件(如果不存在)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python代码雨代码复制_python
- 下一篇: springboot 搭建分布式_爱了!