python文件不存在时创建文件_如果文件不存在,Python中的open()不会创建文件...

回答(16)

avatar.png

2 years ago

好的做法是使用以下内容:

import os

writepath = 'some/path/to/file.txt'

mode = 'a' if os.path.exists(writepath) else 'w'

with open(writepath, mode) as f:

f.write('Hello, world!\n')

avatar.png

2 years ago

所以你想把数据写入文件,但只有它还不存在?

通过使用鲜为人知的x模式来打开()而不是通常的w模式,可以很容易地解决这个问题 . 例如:

>>> with open('somefile', 'wt') as f:

... f.write('Hello\n')

...

>>> with open('somefile', 'xt') as f:

... f.write('Hello\n')

...

Traceback (most recent call last):

File "", line 1, in

FileExistsError: [Errno 17] File exists: 'somefile'

>>>

如果文件是二进制模式,请使用mode xb而不是xt .

avatar.png

2 years ago

我认为这是r,而不是rw . 我'm just a starter, and that'是我在文档中看到的 .

avatar.png

2 years ago

>>> import os

>>> if os.path.exists("myfile.dat"):

... f = file("myfile.dat", "r+")

... else:

... f = file("myfile.dat", "w")

r表示读/写

avatar.png

2 years ago

'''

w write mode

r read mode

a append mode

w+ create file if it doesn't exist and open it in write mode

r+ create file if it doesn't exist and open it in read mode

a+ create file if it doesn't exist and open it in append mode

'''

例:

file_name = 'my_file.txt'

f = open(file_name, 'w+') # open file in write mode

f.write('python rules')

f.close()

我希望这有帮助 . [仅供参考使用python版本3.6.2

avatar.png

2 years ago

import os, platform

os.chdir('c:\\Users\\MS\\Desktop')

try :

file = open("Learn Python.txt","a")

print('this file is exist')

except:

print('this file is not exist')

file.write('\n''Hello Ashok')

fhead = open('Learn Python.txt')

for line in fhead:

words = line.split()

print(words)

avatar.png

2 years ago

open('myfile.dat', 'a') 适合我,很好 .

在py3k你的代码引发 ValueError :

>>> open('myfile.dat', 'rw')

Traceback (most recent call last):

File "", line 1, in

open('myfile.dat', 'rw')

ValueError: must have exactly one of read/write/append mode

在python-2.6中它引发了 IOError .

avatar.png

2 years ago

使用:

import os

f_loc = r"C:\Users\Russell\Desktop\ip_addr.txt"

if not os.path.exists(f_loc):

open(f_loc, 'w').close()

with open(f_loc) as f:

#Do stuff

确保在打开文件后关闭它们 . with 上下文管理器将为您执行此操作 .

avatar.png

2 years ago

从python 3.4开始,你应该使用 pathlib 到"touch"文件 .

它比这个帖子中提出的解决方案更优雅 .

from pathlib import Path

filename = Path('myfile.txt')

filename.touch(exist_ok=True) # will create file, if it exists will do nothing

file = open(filename)

目录也一样:

filename.mkdir(parents=True, exist_ok=True)

avatar.png

2 years ago

将W写入文件,截断(如果存在),r读取文件,创建一个(如果不存在但不写入(并返回null))或创建新文件或附加到现有文件 .

avatar.png

2 years ago

以下方法的优点是文件 properly closed 在块's end, even if an exception is raised on the way. It' s相当于 try-finally ,但更短 .

with open("file.dat","a+") as f:

f.write(...)

...

a打开文件以进行追加和读取 . 如果文件存在,则文件指针位于文件的末尾 . 该文件以追加模式打开 . 如果该文件不存在,则会创建一个用于读写的新文件 . -Python文件模式

f.seek(pos [, (0|1|2)])

pos .. position of the r/w pointer

[] .. optionally

() .. one of ->

0 .. absolute position

1 .. relative position to current

2 .. relative position from end

只允许“rwab”字符;必须有一个“rwa” - 请参阅Stack Overflow问题Python文件模式的详细信息 .

avatar.png

2 years ago

我的答案:

file_path = 'myfile.dat'

try:

fp = open(file_path)

except IOError:

# If not exists, create the file

fp = open(file_path, 'w+')

avatar.png

2 years ago

你想用文件做什么?只写入它或同时读写?

'w','a'将允许写入,如果文件不存在,将创建该文件 .

如果需要从文件中读取,则必须在打开文件之前存在该文件 . 您可以在打开它之前测试它的存在或使用try / except .

avatar.png

2 years ago

将“rw”改为“w”

或使用'a'进行追加(不删除现有内容)

avatar.png

2 years ago

你应该使用 open 与 w+ 模式:

file = open('myfile.dat', 'w+')

avatar.png

2 years ago

如果你想打开它来读写,我假设你不想在打开它时截断它,你希望能够在打开文件后立即读取它 . 所以这是我正在使用的解决方案:

file = open('myfile.dat', 'a+')

file.seek(0, 0)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值