Create file in python code using file object

In this tutorial you will learn how to work with python file object, create file using python script, read from file, write to file in python code.

How to create file in python

Python provides an in-built function for creating, reading and writing files. Here is just one line of code to create file in python with any name you want. But, before we write any real-time example you need to understand few keys.

def CreateFile(self):
    file = open("webTrainingRoom.txt","w+");

In python, we don't need to access any library to handle files, using all built-in function we can handle all file system related operations.

  • Open is the built-in method to create file, the first argument it takes as file name
  • Second argument “w” , indicates that we want to write
  • "W+" means, Create the file if not exist
  • There are few other option you need to remember while writing code for file operation, like "r" for read, and "a" for append

You will learn following topics about file handling in python.

  • Create a file in Python
  • Write a file in Python
  • Append a file in Python
  • Read a file in Python

Python file write and writelines method

Now we see how to write in a file in python, so we open an existing file or create a new one and write some text in that

file = open("webTrainingRoom.txt","w+");
file.write("I am learning pyhton at WebTrainingRoom, Super Excited. ");
    for i in range(10):
        file.writelines("Line Number %d\r\n" % (i+1))

Now if you see in above example i have used both method for writing some content inside the file, write and writelines.

Actually both methods are designed for different purpose of writing.

  • write method expects a single string.
  • writelines method expects an array of strings
Create file under a folder in Python

Now let’s say, you want to create a file in a specific folder, then the approach will be little different, now we create the folder if folder does not exist.

To work with folder we need to have os library reference like import os

import os

class FSOExample(object):

    def __init__(self):
        self.Title = "File System Handling Example";

    def CreateFile(self):
      path = os.getcwd()
      #Create directory
      if not os.path.exists(path):
      file = open(os.path.join(path, "webTrainingRoom.txt"),"w+");
      file.write("I am learning pyhton at WebTrainingRoom, Super Excited.");

Before creating any folder make sure to check if the folder already not exists in python code, otherwise it will throw error.

Now, with the code below we create the file under “logs” folder.

file = open(os.path.join(path, "webTrainingRoom.txt"),"w+");

To get the current application folder path use os.getcwd(), then you can append your subfolder and file absolute path to access the file in python code like example below.

url =path+ "\\testdata\\webTrainingRoom.txt"

If you don't specify any folder location like first example, then the file will be created in root of the application.

Append file in Python

Now we see how to append content in a file using python code, we open an existing file and add some more additional text in that.

Look at the code below, we are opening file using open command, first parameter is the file path and then second parameter "a" indicates that we are opening the file for appending, and "a+" indicates that if the file does not exist then create the file.

file = open(os.path.join(path, "webTrainingRoom1.txt"),"a+");
file.write("adding some new content to file.");

After executing the above code if you check the file, you will see that the new line has been appended, make sure you close the file instance once done.

Read file in Python

Now you learn how to read a file in python, in this example we simply open a file and read all content inside that.

There are two methods readlines() and readline()

file = open("webTrainingRoom.txt","r");
content =file.readlines();
print("Reading successful")

We also can specify the line number we want to read

file = open("webTrainingRoom.txt","r");

To work with file system and directory, there are all built-in methods in python file system object, but while working with path, you need to import operating system library using import os.

Handle File in Python
Learn python programming with free python coding tutorials.
Other Popular Tutorials
Python File Handling
Python programming examples | Join Python Course