File Handling
Opening a file
thefile=open("sample.txt","r")
Here we are creating a file object name “thefile” and assigning the data in the “sample.txt” to it. The “r” parameter says that the file is opened as read-only.
Other arguments are:
- r – Open file for reading only. File pointer is placed at the beginning of the file.
- rb – Open file for reading only in binary format. File pointer is placed at the beginning of the file
- r+ – Open file for both reading and writing. File pointer is placed at the beginning of the file
- rb+ – Open file for both reading and writing in binary format. File pointer is placed at the beginning of the file
- w – Open file for writing only. Overwrites the file if exists. If not create a new file.
- wb – Open file for writing only in binary format. Overwrites the file if exists. If not create a new file.
- w+ – Open file for both reading and writing. Overwrites the file if exists. If not create a new file.
- wb+ – Open file for both reading and writing in binary format. Overwrites the file if exists. If not create a new file.
- a – Open file for appending. File pointer is placed at the end of the file if the file exist. If not create new file.
- ab – Open file for appending in binary format. File pointer is placed at the end of the file if the file exist. If not create new file.
- a+ – Open file for appending reading. File pointer is placed at the end of the file if the file exist. If not create new file.
- ab+ – Open file for appending reading in binary format. File pointer is placed at the end of the file if the file exist. If not create new file.
Reading a file
thefile.read(10)
This code will read the first 10 bytes of the file object “thefile”. If you haven’t define the number of bytes to be read, Python will try to read as much as possible.
The owner of www.ksoftlabs.com will not be liable for any errors or omissions in this information nor for the availability of this information. The owner will not be liable for any losses, injuries, or damages from the display or use of this information.
This terms and conditions are subject to change at anytime with or without notice.