Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for File handling in Python
Adarsh Rawat
Adarsh Rawat

Posted on • Edited on

     

File handling in Python

In this Article we going to learn following topics :

  • Read data from afile.
  • Write data to afile .
  • Append Data to afile.
  • Delete afile.

We're going to cover each of the above point with meaningful examples.

Inpythonopen() function is used to perform variousoperations on files, operation such as
(read,write,append,delete).

open()

Syntax :-open(filename, mode)

Theopen() function takes two argumentfilename andmode, and return aTextIOWrapper class object.

There are four different modes available :-

  • r mode is the default when no mode passed, used to read file, it throwsFileNotFoundError if the file passed in first argument does not exist.

  • w mode is write data into a file, if data exist in thefile it removes that data then, start writing the data into the file , if thefilename passed does not exist,it creates a new file.

  • a mode write data to existingfile, creates a file if it does not exist.

  • delete file with specifiedfilename usingos module ,if the file does not exist it throwsFileExistsError error.

Other then that , you are specify the mode in which file will we handled.

  • t in Text mode.
  • b in Binary mode.

  • For Example :-

file1 = open("file.txt",'wb') # means write in binary modefile2 = open("file.txt",'wt') # means write in text mode
Enter fullscreen modeExit fullscreen mode

Default mode isText mode

After doing all the operation on file use can callfile.close() method to close a file.

Throughout the examples we're going to us the below file

  • filename :- students.txt
Name : Ram KumarAge  : 13City : AjmirName : Alice PenAge  : 12City : BostonName : Marcus LeeAge  : 15City : Tokyo
Enter fullscreen modeExit fullscreen mode

Read data from file

file = open("students.txt",'r')for line in file:    print(line,end="")file.close()Output :-Name : Ram KumarAge  : 13City : AjmirName : Alice PenAge  : 12City : BostonName : Marcus LeeAge  : 15City : Tokyo
Enter fullscreen modeExit fullscreen mode

In the above code , usedfor to the read one line at a time and print it, we're addedend="" in print statement because , in file , a line ends with\n implicitly.

Write data to file

file = open("students_2.txt",'w')student_info = {     "Name" : "Mike Javen",    'Age' : 15,    'City' : 'Minisoda'}for field,data in student_info.items():    file.write(f"{field} : {data}  \n")file.close()students_2.txt file content :-Name : Mike Javen  Age : 15  City : Minisoda
Enter fullscreen modeExit fullscreen mode

Here, we have usedwrite() function , new filestudents_2.txt gets created, because it does not exist in the first place ,and we have added a student info to that file, we not added this student data tostudents.txt file because inw mode the data in the file first gets deleted and then writing starts.

Append data to file

file = open("students.txt",'a')students_info = [ {     "Name" : "John Lenon",    'Age' : 14,    'City' : 'Navi Mumbai'     },  {     "Name" : "Sam Dune",    'Age' : 11,    'City' : 'Boston'     }]for student_info in students_info:    file.write("\n")    for field,data in student_info.items():        file.write(f"{field} : {data}  \n")file.close()Students.txt file.content :-Name : Ram KumarAge  : 13City : AjmirName : Alice PenAge  : 12City : BostonName : Marcus LeeAge  : 15City : TokyoName : John Lenon  Age : 14  City : Navi Mumbai  Name : Sam Dune  Age : 11  City : Boston
Enter fullscreen modeExit fullscreen mode

In the above code we added 2 new students details instudents.txt file using 'a' append mode,

Delete a file

import osfilename = 'students_2.txt'os.remove(filename)print(f"successfully deleted file {filename}")Output :-successfully deleted file students_2.txt
Enter fullscreen modeExit fullscreen mode

The above example is fairly simple one in which we import pythonos module to delete the file in the current directory i.e.,students_2.txt if the file does not exist in the diretory it throws errorFileNotFoundError error.

With this we have seen all 4opearation on a file, I'd like to mention another way in which we can perform sameopeartions we talked about, where we does not have to explicitlyclose() the file working with the file.

Alternative way

with open("students.txt",'r') as file:    for line in file:        print(line, end="")Output :-Name : Ram KumarAge  : 13City : AjmirName : Alice PenAge  : 12City : BostonName : Marcus LeeAge  : 15City : TokyoName : John LenonAge : 14City : Navi MumbaiName : Sam DuneAge : 11City : Boston
Enter fullscreen modeExit fullscreen mode

Here, we have usedwith keyword andas alias as soon as the with block ends, the file gets closed implicitly, we can use the samesyntax with other modes

Writing file in Binary Mode

file = open("new_students.txt",'wb')students_info = b'''    "Name" : "Sam Dune",    'Age' : 11,    'City' : 'Boston'     }     '''file.write(students_info)file.close()Output :-    "Name" : "Sam Dune",    'Age' : 11,    'City' : 'Boston'
Enter fullscreen modeExit fullscreen mode

Here we have write bytes to a files

Before Finishing thisArticle I'd like to cover some useful examples of file processing.

Example :-

  • Reading the entire file content and storing it list for further processing
# file content :-#my name is john levi and i#live in boston and study in#xyz univeristy doing majors#in computer science.person_info = [line for line in open('info.txt')]for line in person_info:    print(line,end="")Output :-my name is john levi and ilive in boston and study inxyz univeristy doing majorsin computer science.
Enter fullscreen modeExit fullscreen mode

Here we fetched the content of entire file usinglist compreshension in just single line remember this file could be of 1000 of line for some operation we have to read file again and again, in this way we can just used the file content stored in the list.

Example :-

Reading the file content and storing it content in somecollection like dictionaries datatype

# File Content :-# Ram Kumar , 12 , Indore# Shayam Kumar, 13 , Mumbai# Ajay Kumar, 11 , Delhi# Harris javen, 15 , New Jerseystudents_info = []for line in open("info.txt"):    name, age, city = line.split(',')    student = {        "Name" : name.strip(),        "Age" : age.strip(),        "City" : city.strip()    }    students_info.append(student)print("Content tetched from file and stored in dictionary\n")for student in students_info:    print(student)Output :-Content tetched from file and stored in dictionary{'Name': 'Ram Kumar', 'Age': '12', 'City': 'Indore'}{'Name': 'Shayam Kumar', 'Age': '13', 'City': 'Mumbai'}{'Name': 'Ajay Kumar', 'Age': '11', 'City': 'Delhi'}{'Name': 'Harris javen', 'Age': '15', 'City': 'New Jersey'}
Enter fullscreen modeExit fullscreen mode

with this example we have come to an end hope you all have understood the topics covered in this article.

:-)

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

An aspiring software developer
  • Joined

More fromAdarsh Rawat

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp