Thursday, 11 June 2020

Python Files



# Read an existing file
fl = open('C:/Users/kuldip_s/Documents/Python Scripts/f1.txt', 'r')
s = fl.read()
print(s)
print('File content is - ',s)
fl.close()
Hi,
 I am Kuldip Singh. I live in Bangalore.

Thanks,
Kuldip
File content is -  Hi,
 I am Kuldip Singh. I live in Bangalore.

Thanks,
Kuldip. . .

In [11]:

# create a new file and write in it
fl = open('C:/Users/kuldip_s/Documents/Python Scripts/f2.txt', 'w')
fl.write('This is the second file. It was created as new file')
fl = open('C:/Users/kuldip_s/Documents/Python Scripts/f2.txt', 'r')
print(fl.read())
fl.close()
This is the second file. It was created as new file. . .

In [17]:

# Append into the existing file
fl = open('C:/Users/kuldip_s/Documents/Python Scripts/f2.txt', 'a')
fl.write('. The file was created successfully')
fl = open('C:/Users/kuldip_s/Documents/Python Scripts/f2.txt', 'r')
print(fl.read())
fl.close()
This is the second file. It was created as new file. The file was created successfully. The file was created successfully. The file was created successfully. . .


f = open('C:/Users/kuldip_s/Documents/Python Scripts/file1.txt','r')
s = f.read()
print(s)
Hi,
Hello everyone.
How are you?
Stay in home.
Stay safe.
Go Corona Go.
Thanks,
Kuldip. . .


f = open('C:/Users/kuldip_s/Documents/Python Scripts/file1.txt','r')
s = f.readline()
print(s)
Hi,

. . .

f = open('C:/Users/kuldip_s/Documents/Python Scripts/file1.txt','r')
s = f.readlines()
print(s)
['Hi,\n', 'Hello everyone.\n', 'How are you?\n', 'Stay in home.\n', 'Stay safe.\n', 'Go Corona Go.\n', 'Thanks,\n', 'Kuldip\n']
. . .

f = open('C:/Users/kuldip_s/Documents/Python Scripts/file1.txt','r')
s = f.readline()
s = f.readline()
print(s)
Hello everyone.

. . .

f = open('C:/Users/kuldip_s/Documents/Python Scripts/file1.txt','r')
s = f.readline()
s = f.readline()
s = f.readline()
print(s)
['How are you?\n', 'Stay in home.\n', 'Stay safe.\n', 'Go Corona Go.\n', 'Thanks,\n', 'Kuldip\n']
. . .

f = open('C:/Users/kuldip_s/Documents/Python Scripts/file1.txt','r')
for x in f:
    print(x)
Hi,

Hello everyone.

How are you?

Stay in home.

Stay safe.

Go Corona Go.

Thanks,

Kuldip


No comments: