0% found this document useful (0 votes)
6 views3 pages

Cs.... File Handling

The document provides examples of file operations in Python, including reading from and writing to text, CSV, and binary files. It demonstrates how to open files, read specific characters or lines, append content, overwrite files, and use the pickle module for binary data. Each operation is accompanied by sample code and expected output.

Uploaded by

bg98990021
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views3 pages

Cs.... File Handling

The document provides examples of file operations in Python, including reading from and writing to text, CSV, and binary files. It demonstrates how to open files, read specific characters or lines, append content, overwrite files, and use the pickle module for binary data. Each operation is accompanied by sample code and expected output.

Uploaded by

bg98990021
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Text file

#demofile.txt (text file)


‘“Hello! My name is Riddhi.
Good Luck!”’

To open the file


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

output:
Hello! My name is Riddhi.
Good Luck!

Return the 5 first characters :


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

output:
Hello

Read one line:


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

output:
Hello! My name is Riddhi.

Seek function:
f = open("demofile.txt", "r")
f.seek(4)
print(f.readline())

output:
o! My name is Riddhi
Tell function:
f = open("demofile.txt", "r")
print(f.readline())
print(f.tell())

output:
Hello! My name is Riddhi.
26

Open the file "demofile2.txt" and append


content:
f = open("demofile2.txt", "a")
f.write("roll.no 31")
f.close()

output:
Hello! My name is Riddhi.
Good Luck! roll.no 31

Open the file and overwrite the content:


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

output:
I have deleted the content!

Csv file
#Data.csv (csv file)
“’Hello! My name is Riddhi.
Good Luck!”’

Read data
import csv as c:
with open(‘Data.csv’ , ‘r’) as m:
d=c.reader(m)
for i in d:
print(i)
output:
Hello! My name is Riddhi.
Good Luck!
Write data:
import csv as c:
with open(‘Data.csv’ , ‘w’) as m:
d=c.writer(m)
d.writerow(“roll no. 31”)

output:
Hello! My name is Riddhi.
Good Luck!
roll no. 31

binary file

load function:
import pickle:
with open(‘Data.dat’ , ‘rb’) as m:
x= pickle.load(m)
if x[2]== “My”:
print(x)

output:
Hello! My name is Riddhi.
Good Luck!

Dump function:
import pickle:
with open(‘Data.dat’ , ‘wb’) as m:
x= “roll no. 31”
pickle.dump(x, m)

output:
Hello! My name is Riddhi.
Good Luck!
roll no. 31

You might also like