How to open and work a File in python
Introduction
In this blog we are going to see how to open a file using python and do operations like:
1. Reading data from files
2. Writing data to files
3. appending data to files
Opening files:
To work in a file we first need to open the file. It is done by using the open() function as per one of the following syntaxes:
For example:
```
myfile = open("taxes.txt")
or
by assigning the file object and the default mode(read mode) to open
file2= open("data.txt", "r") ```
Important things to know before entering into file handling in python :
The first parameter for the open() function is a path to the file you'd like to open. If just the file name is given, then python searches for the file in the current folder
The second parameter of the open() function corresponds to a mode which is typically read("r"), write("w") or append("a") . If no second parameter is given, then by default it opens in read mode
Reading from text files:
1. read(): This function reads the entire data in the file at a time and returns in the format of a string
** Syntax: <filehandle>.read([n])**
2. readline(): It reads the specific amount of line passed has a parameter(n) and it will return output in the form of a string
** Syntax: <filehandle>.readline([n])**
- readlines(): It reads all the lines and returns them a list
### Writing onto Text Files:** Syntax: <filehandle>.read([n])**
- write(): writes string (str1) to file referenced by
**Syntax : <filehandle>.write(str1)**
2.writelines() : writes all srtings in the list(L) as lines to file refernced by
** Syntax: <filehandle>.write(L)**