Python File Methods
This article contains all methods regarding opening, reading, writing and closing files
close()
Closes the file
f = open("demofile.txt", "r") print(f.read()) f.close()
detach()
Returns the separated raw stream from the buffer
f = open("demofile.txt", "r") print(f.detach())
fileno()
Returns a number that represents the stream, from the operating system’s perspective
f = open("demofile.txt", "r") print(f.fileno())
flush()
Flushes the internal buffer
f = open("myfile.txt", "a") f.write("Now the file has one more line!") f.flush() f.write("...and another one!")
isatty()
Returns whether the file stream is interactive or not
f = open("demofile.txt", "r") print(f.isatty())
read()
Returns the file content
f = open("demofile.txt", "r") print(f.read())
readable()
Returns whether the file stream can be read or not
f = open("demofile.txt", "r") print(f.readable())
readline()
Returns one line from the file
f = open("demofile.txt", "r") print(f.readline())
readlines()
Returns a list of lines from the file
f = open("demofile.txt", "r") print(f.readlines())
seek()
- Change the file position
f = open("demofile.txt", "r") f.seek(4) print(f.readline())
seekable()
- Returns whether the file allows us to change the file position
f = open("demofile.txt", "r") print(f.seekable())
tell()
- Returns the current file position
f = open("demofile.txt", "r") print(f.tell())
truncate()
- Resizes the file to a specified size
f = open("demofile2.txt", "a") f.truncate(20) f.close() #open and read the file after the truncate: f = open("demofile2.txt", "r") print(f.read())
writable()
- Returns whether the file can be written or not
f = open("demofile.txt", "a") print(f.writable())
write()
- Writes the specified string to the file
f = open("demofile2.txt", "a") f.write("See you soon!") f.close() #open and read the file after the appending: f = open("demofile2.txt", "r") print(f.read())
writelines()
Writes a list of strings to the file
f = open("demofile3.txt", "a") f.writelines(["See you soon!", "Over and out."]) f.close() #open and read the file after the appending: f = open("demofile3.txt", "r") print(f.read())