Hello guys, to get the most value of this article, please play with the given code in this article.you can’t master just by reading this article. right?
I promise you that If you read and practice the whole article thoroughly, you can write code easily for reading and writing files in python
[irp posts=”512″ name=”Introduction To Python Web Scraping Tutorial Using BeautifulSoup”]
In any programming language, we generally need to do many file handling operations.
For every high-level programming language, there will be a pre-built open() function.The main objectives of this function are read, write, append (end of the line) etc.
Let’s know how this open() function will exactly work to achieve the above objectives.
Basically, when we execute an open() function, it acts like a Python object.As we know that, every object has some methods and attributes, we have some attributes or modes in the Python open() function.
We are going to do many file handling operations (reading and writing files in python ) by using these modes in Python.Okay, I will tell you about these modes soon 🙂
What You Need To Know About the File Types:
A file can be anything whether it is an executable, image and document etc.Python just considers them or put them into two categories, those are:
- Text file
- Binary file
Simply, A text file has some group of characters or sequences of lines where those are terminated by an (EOL) mostly ‘,’ or ‘/’.These are helpful to make an interpreter to start a new line or terminating the file.
Now, another one binary file is that which is not a text file simply it can be an image file.
Python has the ability to read, write or create binary files with its pre-built functions and attributes.
Introduction To Open() Function Syntax
As I said before, Every object has its own attributes.So, We need to give some arguments while read, write or access the file object in python.
If you observe the below pic shows us what arguments can be given for open function those are:
But except file and mode arguments we don’t bother much about other arguments and they will take none as default values
In the below code, I created an object called file with two arguments only called filename and mode.Leave remaining and let them take the default values.
The mode argument will help us in which way a file can be accessed.These are the available modes:
|r||To read files – file should be created already|
|w||To write files – to create and write content to the files – Will erase the previous data|
|a||Appending to an existing file – end of the line (previous data will not be deleted )|
|r+||If you want to perform both the actions (read and write) then this will be useful|
Note: If you want to read and append the files then we have to use a+
How To Create A Text File
I assumed that now you have some idea about the file, file types, and modes in Python.Let’s get started and create our own file.
In the above code, I created a text file called firstFile.txt with a “w” (write) mode.Now in the next two lines, we are writing some text to that file.
Then we are going to close it.Now run the program so that we should have the firstFile.txt file in the same directory where the code is being presented.
How To Read A Text File In Python
In the above section, we have created a file and wrote some lines to it.In this section, we are going to print/read those lines on Python console.For Python read operations, replace the mode with “r”.
Here, the read() function used to read all the data presented in a certain file.And, the print function is going to print that data to console.
we can use the read(n) function to read specific length of characters(including spaces).In the above example, I have given that, this code should read up-to 17 characters only.So Here is the output.
In the above examples, We have read all the data in a file and up to the specific length of characters.What If you would like to read them line by line so that it doesn’t look like messy.
The above file printed only the first line of the text file what if you want to print the next file.We will see that in the next section.
The above code will be going to read and print the second line of the file.We can give certain line numbers as per our wish.
In these two examples we have read the single line by giving the line number but what If we have to read all the lines at a time will be discussed in the next section.
The above code would return the Python List of all the lines in that text file.
output: ['Hello world \n', 'This is my first file'] If we want to print all the elements in the above list we need to iterate through it.Please refer the below code.
Hello world This is my first file
How To Use With Statement in python file handling operations
There is another way to create and handle files in Python programming language.Unlike, above method, we are not going to use any assignment operator here.
write operation using with statement
Here, We didn’t use any assignment operator.Instead, we are using with and as.And, everything will remain as same as above sections.
Read Operation Using With Statement
How To Split Lines into List Of Words with Python
In the above code,
- In the line one, we are opened a text file with “r” mode
- In the second line, we assigned all the lines (Probably, A Python list) to a variable called lines
- We are iterating through the every line in the lines variable
- Now we are going to split the sentence into a list of words by using the split() function.
Note: We have to intend the blocks that come after colon(:)
If you have any doubts, errors or any queries regarding reading and writing files in python .Please comment below or contact me.I’m happy to help you.Please join our Facebook Group
[irp posts=”921″ name=”Python Write To File | How To Write Files In Python”]