NEW_user 2020
NEW_user 2020

Reputation: 65

How to write a file then read from it at same time?

How to write a file then read it knowing that I have to write it first because file does not exist when,I use the option 'r+' but I got the error file does not exist.

with open(file,'w') as f:
    f.write("")
with open(file,'r') as f:
    out = f.read()

Any Solution?

Upvotes: 0

Views: 121

Answers (1)

myeongkil kim
myeongkil kim

Reputation: 2576

try this code

file = "test.txt"
try:
    with open(file, 'r') as f:
        print(f.read())
except IOError:
    with open(file, 'w') as f:
        f.write("")
  1. If file exists
    -> The file is read normally by try, and the read result is output.

  2. If the file does not exist
    -> Try reading the file, but if it doesn't, an IOError is raised.
    -> When an IOError occurs, it writes the file to the filePath immediately


Logic to read after writing file

import os.path

file = 'test.txt'

try:
    if not os.path.isfile(file):
        with open(file, 'w') as f:
            f.write('asd')

    with open(file, 'r') as f:
        print(f.read())
except IOError:
    print('IOError')

Upvotes: 1

Related Questions