Python File Handling
Python File Handling
Python File Handling
The open() function returns a file object, which has a read() method for reading the
content of the file:
f = open("demofile.txt", "r")
print(f.read())
f = open("D:\\myfiles\welcome.txt", "r")
print(f.read())
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))
To read lines-
f = open("demofile.txt", "r")
print(f.readline())
f = open("demofile.txt", "r")
print(f.readline())
print(f.readline())
f = open("demofile.txt", "r")
for x in f:
print(x)
Close Files-
f = open("demofile.txt", "r")
print(f.readline())
f.close()
f = open("demofile2.txt", "a")
f.write("Now the file has more content!")
f.close()
f = open("demofile3.txt", "w")
f.write("Woops! I have deleted the content!")
f.close()
"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