Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (47.6k points)

I need help with Python. I'm trying to open a file, and if the file doesn't exist, I need to create it and open it for writing. I have this so far:

#open file for reading 

fn = input("Enter file to open: ") 

fh = open(fn,'r') 

# if file does not exist, create it 

if (!fh) 

fh = open ( fh, "w")

The error message says there's an issue on the line if(!fh). Can I use exist like in Perl?

1 Answer

0 votes
by (106k points)

You can use the below-mentioned code to create a file if it does not exit:-

import os 

if not os.path.exists('/tmp/test'): 

os.mknod('/tmp/test')

To know more about this you can have a look at the following video tutorial:-

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...