Intellipaat Back

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

In python, I'm rehearsing the management of .txt files. I've been finding out about it and found that in the event that I attempt to open a file that doesn't exist yet it will make it to a similar directory, from which the code is executed. The issue comes that when I attempt to open it, I get this error:

IOError: [Errno 2] No such file or directory: 'C:\Users\myusername\PycharmProjects\Tests\copy.txt'.

I also tried by specifying the path,

import os

THIS_FOLDER = os.path.dirname(os.path.abspath(__file__))

my_file = os.path.join(THIS_FOLDER, 'copy.txt')

1 Answer

0 votes
by (26.4k points)

Seems like you forgot the mode. 

try w:

file = open("copy.txt", "w") 

file.write("Your text goes here") 

file.close() 

default value here is r, if the file is not there it will fail.

'r' open for reading (default)

'w' open for writing, truncating the file first

Other options are,

'x' open for exclusive creation, failing if the file already exists

'a' open for writing, appending to the end of the file if it exists

You can also execute with the help of with statement.

with open("copy.txt", "w") as file:

    file.write("Your text goes here")

Want to know more details related to python? Join python certification course and get certified.
Watch this video tutorial on how to become a professional in python...

Related questions

0 votes
1 answer
asked Feb 24, 2021 in Python by laddulakshana (16.4k points)
0 votes
1 answer
0 votes
2 answers
0 votes
1 answer
0 votes
2 answers

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...