When you open a file for reading in python if the file does not 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 bottom line is, I just need a solution for the problem. I am curious about the other stuff, but all I need is a nice way to do the opening part.

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.

When you open a file for reading in python if the file does not exist?

Neuron

4,5854 gold badges32 silver badges53 bronze badges

asked Jun 3, 2010 at 15:05

3

You should use open with the w+ mode:

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

When you open a file for reading in python if the file does not exist?

Igor Chubin

58.5k10 gold badges117 silver badges138 bronze badges

answered Jun 3, 2010 at 15:12

muksiemuksie

11.9k1 gold badge18 silver badges14 bronze badges

9

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.dat","a+") as f:
    f.write(...)
    ...

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.

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

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

answered Mar 12, 2013 at 11:06

QwertyQwerty

25.9k21 gold badges101 silver badges124 bronze badges

7

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

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]

When you open a file for reading in python if the file does not exist?

bad_coder

9,39619 gold badges37 silver badges61 bronze badges

answered Dec 30, 2017 at 16:26

When you open a file for reading in python if the file does not exist?

1

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

answered May 4, 2015 at 1:49

lollercoasterlollercoaster

15.1k34 gold badges106 silver badges168 bronze badges

2

Change "rw" to "w+"

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

answered Jun 3, 2010 at 15:12

baloobaloo

7,4974 gold badges25 silver badges35 bronze badges

0

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)

answered Apr 23, 2018 at 6:29

When you open a file for reading in python if the file does not exist?

GranitosaurusGranitosaurus

19.5k4 gold badges53 silver badges76 bronze badges

6

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

r+ means read/write

answered Jun 3, 2010 at 15:18

KhorkrakKhorkrak

3,8291 gold badge26 silver badges34 bronze badges

3

My answer:

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

answered May 27, 2014 at 6:20

Chien-Wei HuangChien-Wei Huang

1,7351 gold badge17 silver badges27 bronze badges

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.

answered Feb 2, 2015 at 19:36

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.

answered Jan 30, 2021 at 0:27

When you open a file for reading in python if the file does not exist?

2

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.

answered Jun 3, 2010 at 15:11

SilentGhostSilentGhost

294k64 gold badges301 silver badges291 bronze badges

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

When you open a file for reading in python if the file does not exist?

Neuron

4,5854 gold badges32 silver badges53 bronze badges

answered Jun 22, 2013 at 12:16

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.

When you open a file for reading in python if the file does not exist?

Neuron

4,5854 gold badges32 silver badges53 bronze badges

answered Jun 3, 2010 at 15:29

user49117user49117

7763 silver badges9 bronze badges

2

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.

answered Oct 11, 2015 at 20:10

Gustavo6046Gustavo6046

3927 silver badges17 bronze badges

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)

answered Jan 12, 2018 at 13:26

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.

answered Dec 14, 2017 at 13:58

When you open a file for reading in python if the file does not exist?

0

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)

answered Aug 8, 2018 at 5:45

When you open a file for reading in python if the file does not exist?

What happens if a file doesn't exist when you open it for reading?

If you open a file for reading and the file doesn't exist, then an exception is thrown. If you open a file for writing and the file doesn't exist, then the file is created with 0 length.

What happens if you try to open a file for reading that doesn't exist Python?

When we use a+ it 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.

What happens if file is not found in Python?

If you reference a file that does not exist, Python will return an error. One type of error is the FileNotFoundError, which is raised when referencing a file that does not exist using the os library.

How do you handle file does not exist in Python?

If the file does not exist python.
In this example, I have imported a module called pathlib. The module pathlib is used to work with files and directories..
The pathlib. path is used to join the path of the two directories..
The path. exists() is used to check whether the file exists are not..
The path..