Python ENG It is the most used language in Artificial Intelligence and the necessary document sharing areas are shared here.


Python - Working With Files

Dolyetyus - ait Kullanıcı Resmi (Avatar)
International Expert Moderator
Üyelik tarihi:
Teşekkür (Etti):
Teşekkür (Aldı):
(0) %
3 Gün önce
Greetings TurkHackTeam Members, in this tutorial I will show you how to use files in your python projects.

First of all, file handling is an important part of any web application.

Python has several functions for creating, reading, deleting et cetera.

File Methods

The key function for working with files in Python is the open() function.
The open() function takes two parameters; filename, and mode.
There are four different methods for opening a file:
  • "r" -Read: Default value. Opens a file for reading, error if the file does not exist
  • "a" -Append: Opens a file for appending, creates the file if it does not exist
  • "w" -Write: Opens a file for writing, creates the file if it does not exist
  • "x" -Create: Creates the specified file, returns an error if the file exists

Also you can specify if the file should be handled as binary or text mode

"t" - Text: Default value. Text mode

"b" - Binary: Binary mode

To open a file for reading it is enough to specify the name of the file:

f = open("xxx.txt")

The code above is the same as:

f = open("xxx.txt", "rt")

Because "r" for read, and "t" for text are the default values, you do not need to specify them.

Opening Files

To open the file, we can use the built-in open() function.

The open() function returns a file object, which has a read() method for reading the content of the file:

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

If the file is located in a different Iocation, you will have to specify the file path, like this:

f = open("D:\\file\xxx.txt", "r")

Reading Specified Parts

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

This code will only print first 10 characters of our file.

Reading Lines

Well, you can return one line by using the readline() method:

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

If you call readline() two times, you can read the two first lines:

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

By looping through the lines of the file, you can read the whole file, line by line:

f = open("demofile.txt", "r")
while True:

Closing Files

You can also close the files by using python. All you need to do is using close().

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

Important: You should always close your files, sometimes due to buffering, changes made to a file may not show until you close the file.

Writing Files

To write to an existing file, you must add a parameter to the open() function:

"a" - Append: will append to the end of the file
"w" - Write: will overwrite any existing content

Let us open the file "xxx123.txt" and append content to the file:

f = open("xxx123.txt", "a")
f.write("File file file!")

#open and read the file after the appending:
f = open("xxx123.txt", "r")

Now let us open the file "yyy123.txt" and overwrite the content:

f = open("yyy123.txt", "w")
f.write("Woops! I have deleted the content!")

#open and read the file after the appending:
f = open("yyy123.txt", "r")

Important: the "w" method will overwrite the entire file.

Creating Files

To create a new file in Python, we can use the open() method, with one of the following parameters:

"x" - Create: will create a file, returns an error if the file exist
"a" - Append: will create a file if the specified file does not exist
"w" - Write: will create a file if the specified file does not exist

Let's create a file called "tht.txt":

f = open("tht.txt", "x")

So a new empty file is created!

Now let's create a new file if it does not exist:

f = open("myfile.txt", "w")

It's done. Let's move to the next part.

Deleting Files

To delete a file, we must import the OS module, and run its os.remove() function:

Let us try to remove the file "tht1.txt":

import os

For avoıding getting an error, we might want to check if the file exists before we try to delete it:

import os
if os.path.exists("demofile.txt"):
print("The file does not exist")

Also to delete an entire folder, we can use the os.rmdir() method:

import os

Important: You can only remove empty folders.

Well, that was all. Thanks for reading. Have a good day.
RegTa Teşekkür etti.


« Önceki Konu | Sonraki Konu »