File Handling - Python Programming Basics

Creating and reading files is easy with Python. It takes only a couple of lines of code.

The main function you need to remember in order to handle files with Python is the open function. By using the open function you can open the file in the appropriate mode (reading, writing, appending, etc.) to do the needful.

Let's the syntax with the following line of code

{C}{C}

{C}{C}

f = open("sample.txt","r")

{C}{C}

{C}{C}

The first parameter is the name of the file to created/manipulated. The second parameter is the file mode. A file can be manipulated in different ways i.e write, read, append, etc.

{C}{C}

{C}{C}

The three most essential file modes you need are the following:

{C}{C}

{C}{C}

1) r is used when we need to just get the contents of the file

{C}{C}

{C}{C}

2) w is used when we need to create a new file or remove the existing contents of the file and add the specified content

{C}{C}

{C}{C}

3) a is used when we need to add data to the end of an existing file

{C}{C}

{C}{C}

Creating and adding content to a file:

{C}{C}

{C}{C}

Pass the string to the write method of f (file handler object) to add that string to the file. You can call the write method any number of times separately After you're done with manipulating the file, you need to close the file by calling the close method.

f = open("sample.txt","w")
f.write("First string, ")
f.write("Second string, ")
f.write("and Third string.")
f.close()

Reading the contents of a file:

If you call the read method on the file object, all the contents of the file are returned to you in the form of a single string.

f = open("sample.txt","r")
allFileData = f.read()
print(allFileData)
f.close()

Appending data to an existing file:

If you use the append mode, the existing data of the fill not be truncated. The data you specify in the invocation of the write method will be added to the end of the existing contents of the file.

f = open("sample.txt","a")
f.write("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.")
f.close()

That's how you manipulate files in python. To learn more about the different settings and file modes, visit the official documentation page: https://docs.python.org/3/library/functions.html#open