Python File Handling

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 4

PYTHON FILE HANDLING

 Open a file on the server

To open the file, 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:

#’r’ here specifies the reading mode of the file.

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

If the file is located in a different location, you will have to


specify the file path, like this:

f = open("D:\\myfiles\welcome.txt", "r")
print(f.read())

To read only parts of the file-

By default the read() method returns the whole text, but you can also
specify how many characters you want to return:

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

-It will return 5 first characters of the file.

To read lines-

You can return one line by using the readline() method:

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

To read n lines from the file, use readline(), n times:

Example- To read two lines of the file:

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

Read complete file-


You can read the complete file by looping through the lines of the
file.

f = open("demofile.txt", "r")
for x in f:
  print(x)

Close Files-

You can close the files using close() method.

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

 PYTHON FILE WRITE


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

f = open("demofile2.txt", "a")
f.write("Now the file has more content!")
f.close()

#’w’ will overwrite the existing content.

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

Create a New File-


"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

Writing into a .csv file


Using csv.Writer class
import csv 
    
# field names 
fields = ['Name', 'Branch', 'Year', 'CGPA'] 
    
# data rows of csv file 
rows = [ ['Nikhil', 'COE', '2', '9.0'], 
         ['Sanchit', 'COE', '2', '9.1'], 
         ['Aditya', 'IT', '2', '9.3'], 
         ['Sagar', 'SE', '1', '9.5'], 
         ['Prateek', 'MCE', '3', '7.8'], 
         ['Sahil', 'EP', '2', '9.1']] 
    
# name of csv file 
filename = "university_records.csv"
    
# writing to csv file 
with open(filename, 'w') as csvfile: 
    # creating a csv writer object 
    csvwriter = csv.writer(csvfile) 
        
    # writing the fields 
    csvwriter.writerow(fields) 
        
    # writing the data rows 
    csvwriter.writerows(rows)

Using csv.Dictwriter class


# importing the csv module 
import csv 
    
# my data rows as dictionary objects 
mydict =[{'branch': 'COE', 'cgpa': '9.0', 'name': 'Nikhil', 'year':
'2'}, 
         {'branch': 'COE', 'cgpa': '9.1', 'name': 'Sanchit',
'year': '2'}, 
         {'branch': 'IT', 'cgpa': '9.3', 'name': 'Aditya',
'year': '2'}, 
         {'branch': 'SE', 'cgpa': '9.5', 'name': 'Sagar',
'year': '1'}, 
         {'branch': 'MCE', 'cgpa': '7.8', 'name': 'Prateek',
'year': '3'}, 
         {'branch': 'EP', 'cgpa': '9.1', 'name': 'Sahil',
'year': '2'}] 
    
# field names 
fields = ['name', 'branch', 'year', 'cgpa'] 
    
# name of csv file 
filename = "university_records.csv"
    
# writing to csv file 
with open(filename, 'w') as csvfile: 
    # creating a csv dict writer object 
    writer = csv.DictWriter(csvfile, fieldnames = fields) 
        
    # writing headers (field names) 
    writer.writeheader() 
        
    # writing data rows 
    writer.writerows(mydict) 

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy