Working with files in Python!
- 19-07-2018
- python
Share:
https://techconductor.com/blogs/python/python_working_with_files.php
Copy
Python provides us many different ways to read and write to a file. Here we will see how to use them and how they works.
The easiest way to open a file is to use the python open()
function. While opening a file in the same directory where the script is we use open('file1.txt', 'w')
. To open a file file in specific directory we can provide the raw location link open(r'D:\python_files\file1.txt', 'w')
.
There are few options we can use while opening a file they are shown below:
Mode | Description |
---|---|
'r' | Opens a file in read only mode |
'w' | Opens a file if already exist clears its contents, if not creates a new file |
'x' | Creates a new file, error in case of file already exists |
'a' | Opens file in append mode, If not exist creates a new file |
't' | To open a file in text mode. Its a default mode |
'b' | Open a file in binary mode |
'+' | Open a file in both read and write mode. |
Here is an example:
def f_w(): infile = open('file1.txt', 'w') print(infile.read()) def f_x(): infile = open('file2.txt', 'x') print(infile.read()) def f_a(): infile = open('file3.txt', 'a') print(infile.read()) def f_t(): infile = open('file4.txt', 't') print(infile.read()) def f_b(): infile = open('file5.txt', 'b') print(infile.read()) def f_wp(): infile = open('file6.txt', 'w+') print(infile.read()) def f_ap(): infile = open("file7.txt", "a+") print(infile.read()) f_w() f_x() f_a() f_t() f_b() f_wp() f_ap()
Try the code and see what will be the output. Comment below if you found what will be the result.