trh178
trh178

Reputation: 11638

open() in Python does not create a file if it doesn't exist

What is the best way to open a file as read/write if it exists, or if it does not, then create it and open it as read/write? From what I read, file = open('myfile.dat', 'rw') should do this, right?

It is not working for me (Python 2.6.2) and I'm wondering if it is a version problem, or not supposed to work like that or what.

The enclosing directory was writeable by user and group, not other (I'm on a Linux system... so permissions 775 in other words), and the exact error was:

IOError: no such file or directory.

Upvotes: 970

Views: 1455902

Answers (19)

Ali Seify
Ali Seify

Reputation: 39

sometime error not about code. it's about other problems like os limitations. i had same problem too and try codes for solve that but it's not solve. i tried create file manually but os not allowe i do that. finally i findout problem is about os limitation. so i changed root folder name and problem is solved.

Upvotes: 0

PouriaDiesel
PouriaDiesel

Reputation: 735

I write this function from combination of above answers. you can use this before read and write to create file and it's parent dir. then use it if you want else close it:

import os
import ntpath

def open_even_not_exists(filepath, mode='w+'):
    if not ntpath.isdir(ntpath.dirname(filepath)):
        os.mkdir(ntpath.dirname(filepath))
    if not ntpath.exists(filepath):
        open(filepath, 'w+').close()
    return open(filepath, mode)

if __name__ == "__main__":
   f = open_even_not_exists('file.txt')
   # Do Stuff...
   f.close()

*notice: this worked in my project.You can don't return anything but becareful about close when you copy this function.

Upvotes: 0

Khorkrak
Khorkrak

Reputation: 4009

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

r+ means read/write.

Upvotes: 29

Qwerty
Qwerty

Reputation: 31905

The advantage of the following approach is that the file is properly closed at the block's end, even if an exception is raised on the way. It's equivalent to try-finally, but much shorter.

with open("file.txt","a+") as f:
    f.write("Hello world!")
    f.seek(4)
    f.readline()
    ...

a+ Opens a file for both appending and reading. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing. -Python file modes

seek() method sets the file's current position.

e.g. f.seek(4, 0) with file content "Hello world!" would f.readline() "o world!"

f.seek(pos [, (0|1|2)])
pos .. Number. Position of the r/w pointer
[] .. optionally
() .. one of ->
  0 .. absolute position (default)
  1 .. relative position to current
  2 .. relative position from end

Only "rwab+" characters are allowed; there must be exactly one of "rwa" - see Stack Overflow question Python file modes detail.

Upvotes: 209

Gajendra D Ambi
Gajendra D Ambi

Reputation: 4233

'''
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
'''

Assuming that you are in working directory of the file.

Example:

file_name = 'my_file.txt'
f = open(file_name, 'w+')  # open file in write mode
f.write('python rules')
f.close()

[FYI am using Python version 3.6.2]

Upvotes: 71

Chenglong Ma
Chenglong Ma

Reputation: 384

For Python 3+, I will do:

import os

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

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

So, the problem is with open cannot create a file before the target directory exists. We need to create it and then w mode is enough in this case.

Upvotes: 19

Angel Poppy
Angel Poppy

Reputation: 95

I think it's r+, not rw. I'm just a starter, and that's what I've seen in the documentation.

Upvotes: 7

user49117
user49117

Reputation: 786

What do you want to do with file? Only writing to it or both read and write?

'w', 'a' will allow write and will create the file if it doesn't exist.

If you need to read from a file, the file has to be exist before open it. You can test its existence before opening it or use a try/except.

Upvotes: 6

hostingutilities.com
hostingutilities.com

Reputation: 9499

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

Note: Files have to be closed after you open them, and the with context manager is a nice way of letting Python take care of this for you.

Upvotes: 13

Ganesh Jat
Ganesh Jat

Reputation: 17

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)

Upvotes: -3

muksie
muksie

Reputation: 13043

You should use open with the w+ mode:

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

Upvotes: 1133

Granitosaurus
Granitosaurus

Reputation: 21406

Since python 3.4 you should use pathlib to "touch" files.
It is a much more elegant solution than the proposed ones in this thread.

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)

Same thing with directories:

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

Upvotes: 40

Danilo Souza Morães
Danilo Souza Morães

Reputation: 1593

If you want to open it to read and write, I'm assuming you don't want to truncate it as you open it and you want to be able to read the file right after opening it. So this is the solution I'm using:

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

Upvotes: 4

Stephen Ngethe
Stephen Ngethe

Reputation: 1044

So You want to write data to a file, but only if it doesn’t already exist?.

This problem is easily solved by using the little-known x mode to open() instead of the usual w mode. For example:

 >>> 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 "<stdin>", line 1, in <module>
FileExistsError: [Errno 17] File exists: 'somefile'
  >>>

If the file is binary mode, use mode xb instead of xt.

Upvotes: 2

wallabra
wallabra

Reputation: 442

Put w+ for writing the file, truncating if it exist, r+ to read the file, creating one if it don't exist but not writing (and returning null) or a+ for creating a new file or appending to a existing one.

Upvotes: 4

lollercoaster
lollercoaster

Reputation: 16493

Good practice is to use the following:

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')

Upvotes: 43

Chien-Wei Huang
Chien-Wei Huang

Reputation: 1851

My answer:

file_path = 'myfile.dat'
try:
    fp = open(file_path)
except IOError:
    # If not exists, create the file
    fp = open(file_path, 'w+')

Upvotes: 11

SilentGhost
SilentGhost

Reputation: 319501

open('myfile.dat', 'a') works for me, just fine.

in py3k your code raises ValueError:

>>> open('myfile.dat', 'rw')
Traceback (most recent call last):
  File "<pyshell#34>", line 1, in <module>
    open('myfile.dat', 'rw')
ValueError: must have exactly one of read/write/append mode

in python-2.6 it raises IOError.

Upvotes: 8

baloo
baloo

Reputation: 7755

Change "rw" to "w+"

Or use 'a+' for appending (not erasing existing content)

Upvotes: 35

Related Questions