You are on page 1of 3

FileHandling

September 11, 2020

1 File Handling

[1]: data = """Hi, This is a test file created


To demonstrate the writing reading and appending to a file."""

1.1 Writing to File

[9]: with open('WrittenSample.txt','w') as file_to_write:


file_to_write.write(data)

[10]: !cat WrittenSample.txt

Hi, This is a test file created


To demonstrate the writing reading and appending to a file.

[11]: with open('WrittenSample.txt','w') as file_to_write:


file_to_write.write('Trying to Overwrite the Content')

[12]: !cat WrittenSample.txt

Trying to Overwrite the Content

[13]: with open('WrittenSample.txt','a') as file_to_write:


file_to_write.write('\nAppending to Overwrited Content')

[14]: !cat WrittenSample.txt

Trying to Overwrite the Content


Appending to Overwrited Content

1
1.2 Reading From File

[15]: with open('WrittenSample.txt') as file_to_read:


print(file_to_read.read())

Trying to Overwrite the Content


Appending to Overwrited Content

[19]: with open('WrittenSample.txt') as file_to_read:


print(file_to_read.read(31)) #Trying to read 31␣
,→characters.

Trying to Overwrite the Content

[20]: with open('WrittenSample.txt') as file_to_read:


lines = file_to_read.readlines()
for line in lines:
print(line) #reading line by line

Trying to Overwrite the Content

Appending to Overwrited Content

[21]: with open('WrittenSample.txt') as file_to_read:


lines = file_to_read.readlines()
for line in lines:
for word in line.split():
print(word)

Trying
to
Overwrite
the
Content
Appending
to
Overwrited
Content

[24]: with open('WrittenSample.txt') as file_to_read:


lines = file_to_read.readlines()
for line in lines:
for word in line.split():
print(word, end=' ')
print('')

Trying to Overwrite the Content


Appending to Overwrited Content

2
1.3 Some additional attributes

[26]: print(file_to_read.closed)
print(file_to_write.closed)

True
True

[28]: print(file_to_read.name)
print(file_to_write.name)

WrittenSample.txt
WrittenSample.txt

[29]: print(file_to_read.mode)
print(file_to_write.mode)

r
a

You might also like