Header Ads

Responsive Ads Here

File Handling with Python

 
File Handling with Python



f = open("My_file.txt")   # opens the file (default mode - read mode)
print(f"cursor position : {f.tell()}")   # tells the position of cursor
print(f.read())  # reads the file
print(f"cursor position : {f.tell()}")
f.seek(10)  # changes the position of cursor
print(f.read())
print(f"cursor position : {f.tell()}")
f.seek(0)
print(f.readline())  # reads one line at a time
print(f.readline())
print(f.readline())

f.seek(0)
print(f.readlines())  # reads the lines and returns a list

print(f.closed)   # checks if file is closed or not (True/False)
f.close()   # closes a file
print(f.closed)



# with block
# r  read mode (reads the files)
# w - write mode (deletes previous data and wite new data)
# a - append mode (adds new data to the previous data)
# r+ - read and write mode
with open("My_file1.txt", "r+" ) as f:  # works the same way as f = open("My_file.txt")
                                                # no need to close the file
    f.write("\nDo whatever you love....")
    print(f.read())



with open("My_file.txt") as f1:
    with open("My_file1.txt", "a") as f2:
        f2.write(f1.read())

Powered by Blogger.