Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a new text file using Python

I'm practicing the management of .txt files in python. I've been reading about it and found that if I try to open a file that doesn't exists yet it will create it on the same directory from where the program is being executed. The problem comes that when I try to open it, I get this error:

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

I even tried specifying a path as you can see in the error.

import os THIS_FOLDER = os.path.dirname(os.path.abspath(__file__)) my_file = os.path.join(THIS_FOLDER, 'copy.txt') 
like image 494
Just Half Avatar asked Feb 24 '18 03:02

Just Half


People also ask

How do I create a new txt file?

Another way to create a text file is to right-click an empty area on the desktop, and in the pop-up menu, select New, and then select Text Document. Creating a text file this way opens your default text editor with a blank text file on your desktop. You can change the name of the file to anything you want.

How do you create a new file and write in Python?

To create and write to a new file, use open with “w” option. The “w” option will delete any previous existing file and create a new file to write. If you want to append to an existing file, then use open statement with “a” option. In append mode, Python will create the file if it does not exist.

Is it possible to create a text in Python?

In Python, there is no need for importing external library to read and write files. Python provides an inbuilt function for creating, writing, and reading files. In this file handling in Python tutorial, we will learn: How to Open a Text File in Python.


2 Answers

Looks like you forgot the mode parameter when calling open, try w:

with open("copy.txt", "w") as file:     file.write("Your text goes here") 

The default value is r and will fail if the file does not exist

'r' open for reading (default) 'w' open for writing, truncating the file first 

Other interesting 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 

See Doc for Python2.7 or Python3.6

like image 97
Bentaye Avatar answered Sep 30 '22 09:09

Bentaye


# Method 1 f = open("Path/To/Your/File.txt", "w")   # 'r' for reading and 'w' for writing f.write("Hello World from " + f.name)    # Write inside file  f.close()                                # Close file   # Method 2 with open("Path/To/Your/File.txt", "w") as f:   # Opens file and casts as f      f.write("Hello World form " + f.name)       # Writing     # File closed automatically 

There are many more methods but these two are most common. Hope this helped!

like image 29
r3t40 Avatar answered Sep 30 '22 11:09

r3t40