You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Day 5: File I/O: Reading and Writing Text, CSV, JSON files
Working with Text Files
Used to store data such that it can be retrieved any time
To read or write from a file, the following operations take place:
Open a file
Perform Read or write operations
Close the file
Open a file
f=open('hello.txt', 'r')
First argument is the string containing file name
Second argument is the file opening mode. (r, w, a, etc.)
Default, files are opened in text mode.
Reading from file
f.read(5) # read next 5 bytesf.readline() # read the entire linef.readlines() # read the entire file and return list of linesf.tell() # get the current file positionf.seek(0) # bring file cursor to initial position
Writing to file
f.write("hello world\n")
Closing a file
Frees up the resources tied with the file
f.close()
Need to worry about exceptions if any operation on file is running
Explore skipinitialspace attribute in the reader function.
There can be many other attributes specified and can make code difficult to maintain, so to solve this dialect is provided as another optional parameter, which groups together many formatting patterns.