Python File
Python File
Files in python are used to access external applications (.txt, .csv etc) to fetch data in it to connect to a file we use a function called OPEN in python and provide the file location of the OPEN function as argument and second argument is based on the type of operation we perform as follows:
Mode Explanation
- ‘w’ – It will open the file for writing the data, if the file is not found then it will create a new file and then it will write.
- ‘r’ – It will open the file for reading, if file not found it will returns File Not Found Error.
- ‘a’ – It will open the file for append mode, if the file is not found then it will create a new file and then it will write if found it append the data into that file
- ‘w+’– It will open the file for writing and reading the data if the file is not found then it will create a new file and then it will write
- ‘r+’ – It will open the file for writing and reading if file not found it will return FileNotFoundError error.
- ‘a+’ – It will open the file for reading and append mode, if the file is not found then it will create a new file and it will write if found it append the data into that file
- ‘wb’ – It will open the file for writing the data in binary format, if the file is not found then it will create a new file and then it will write
- ‘rb’ – It will open the file for reading binary if file not found it will returns File Not Found Error.
- ‘ab’ – It will open the file for append mode binary format, if the file is not found then it will create a new file and it will write if found it append the data into that file
- ‘wb+’ – It will open the file for writing and reading the data in binary format if the file is not found then it will create a new file and then it will write
- ‘rb+’ – It will open the file for writing and reading in binary format if file not found it will return File Not Found Error.
- ‘ab+’- It will open the file for reading and append mode binary format, if the file is not found then it will create a new file and then it will write if found it append the data into that file
Example:
file = open("sample.txt")
file object created in the earlier statement is used to perform various operations on a files that contains data, i.e we can open, read and write a file as follows:
<ul “class=list-1”>
- To read – file.read()
- To close – file.close()
- To Open – file.open()
Example to read a file:
file = open('geek.txt', 'r')
for each in file:
print (each) file.close()