Python - Working With Files

Dolyetyus

Co Admin
21 Nis 2020
1,204
664
Delft
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")
print(f.read())


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")
print(f.read())



Reading Specified Parts

f = open("demofile.txt", "r")
print(f.read(10))


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")
print(f.readline())


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

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


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

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



Closing Files

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

f = open("xxx.txt", "r")
print(f.readline())
f.close()


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!")
f.close()

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


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!")
f.close()

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


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
os.remove("tht1.txt")


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"):
os.remove("demofile.txt")
else:
print("The file does not exist")


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

import os
os.rmdir("folder")


Important: You can only remove empty folders.


Well, that was all. Thanks for reading. Have a good day.
 
Üst

Turkhackteam.org internet sitesi 5651 sayılı kanun’un 2. maddesinin 1. fıkrasının m) bendi ile aynı kanunun 5. maddesi kapsamında "Yer Sağlayıcı" konumundadır. İçerikler ön onay olmaksızın tamamen kullanıcılar tarafından oluşturulmaktadır. Turkhackteam.org; Yer sağlayıcı olarak, kullanıcılar tarafından oluşturulan içeriği ya da hukuka aykırı paylaşımı kontrol etmekle ya da araştırmakla yükümlü değildir. Türkhackteam saldırı timleri Türk sitelerine hiçbir zararlı faaliyette bulunmaz. Türkhackteam üyelerinin yaptığı bireysel hack faaliyetlerinden Türkhackteam sorumlu değildir. Sitelerinize Türkhackteam ismi kullanılarak hack faaliyetinde bulunulursa, site-sunucu erişim loglarından bu faaliyeti gerçekleştiren ip adresini tespit edip diğer kanıtlarla birlikte savcılığa suç duyurusunda bulununuz.