Python File Object Example

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.

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 a 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()
      print(path)
      path=path+"/logs/";
      #Create directory
      if not os.path.exists(path):
        os.mkdir(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, 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 path to access the file in python code like example below.

path=os.getcwd()
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.");
file.close()

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(content)
print("Reading successful")

We also can specify the line number we want to read

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

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
Python File Handling
Python programming examples | Join Python Course