如果一个文件存在,那么以读/写的方式打开它,或者如果它不存在,那么创建它并以读/写的方式打开它,最好的方法是什么?从我读到的,file = open('myfile.dat', 'rw')应该这样做,对吗?

它不适合我(Python 2.6.2),我想知道这是版本问题,还是不应该这样工作或其他什么。

最重要的是,我只需要一个解决问题的办法。我对其他的东西很好奇,但我只需要一个好方法来做开头部分。

封闭的目录可由用户和组写入,而不是其他(我在Linux系统上…所以权限775换句话说),准确的错误是:

IOError:没有这样的文件或目录。


当前回答

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)

其他回答

你应该在w+模式下使用open:

file = open('myfile.dat', 'w+')
>>> import os
>>> if os.path.exists("myfile.dat"):
...     f = file("myfile.dat", "r+")
... else:
...     f = file("myfile.dat", "w")

R +表示读/写

Use:

import os

f_loc = r"C:\Users\Russell\Desktop\myfile.dat"

# Create the file if it does not exist
if not os.path.exists(f_loc):
    open(f_loc, 'w').close()

# Open the file for appending and reading
with open(f_loc, 'a+') as f:
    #Do stuff

注意:文件在打开后必须关闭,而with context管理器是让Python为你处理这一问题的好方法。

对于Python 3+,我将这样做:

import os

os.makedirs('path/to/the/directory', exist_ok=True)

with open('path/to/the/directory/filename', 'w') as f:
    f.write(...)

因此,问题在于open不能在目标目录存在之前创建文件。我们需要创建它,在这种情况下w模式就足够了。

'''
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 for reading and writing. Does not create file.
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版本]