Text Files in Python
In this article , Iam going to describe about how you will
create , update, view and delete the text files in Python.
So, let’s start :-
Introduction
Normally, we will use libraries and modules for this in python.
But here
we will do this by a creative ways.
Now, first we need Python’s built-in open function to get file objects.
The open function is use to open file in python.
When you use the open function, it returns file objects. File objects contain methods and attributes that will be used to collect information of the file .It can be used to modify the text file in python.
The mode attribute of a file object tells you which mode a file we want to use like ‘r’, ‘w’ etc And the name attribute is the name of the file which we have text content’s that the file object used.
Now, first we need Python’s built-in open function to get file objects.
The open function is use to open file in python.
When you use the open function, it returns file objects. File objects contain methods and attributes that will be used to collect information of the file .It can be used to modify the text file in python.
The mode attribute of a file object tells you which mode a file we want to use like ‘r’, ‘w’ etc And the name attribute is the name of the file which we have text content’s that the file object used.
File Types
In Linux/Windows, File’swill be manipulated, updatedand
created by the user/OS. files could be images, text documents and much more.
In Python, a file is categorized as either text or binary,
and the difference between the two file types is important.
Text files are structured as a sequence of lines, where
each line includes a sequence of characters. This is what you know as code or
syntax.
Each line is terminated with a special character, called
the EOL or End of Line character. There are several
types, but the most common is the comma {,} or newline character. It ends the
current line and tells the interpreter a new one has begun.
A backslash(\) character can also be used, and it tells
the interpreter that the next character – following the slash – should be
treated as a new line. This character is useful when you don’t want to start a
new line in the text itself but in the code.
A binary file is any type of file except text Because of
their nature, binary files can only be processed by an application that know or
understand the file’s structure. There will be some applications that can read
and interpret binary.
Open ( ) Function
To open the file contents we have to use the
built-in open ()function.
open ( )will return a file object,
so it is used with two arguments.
An argument is nothing more than a value that has been
provided to a function, which is called when you call it. So, if we declare the
name of a file as “File content” that name would be considered an argument.
The syntax to open a file object
in Python is: -
file = open(“filename”, “mode”) where file is the variable to add
the file object.
The second argument you see – mode–
tells the interpreter and developer which way the file will be used.
Mode
Including a mode argument is optional but a default value of ‘r’is assumed by the python.
if it is omitted. Then the‘r’
value stands for read mode, which is just one of many.
The modes are :-
·
‘r’
– Read mode which is used when the file is only being read.
·
‘w’
– Write mode which is used to edit and write new information to the file
(any existing files with the same name will be erased when this mode is
activated).
·
‘a’
– Appending mode, which is used to add new data to the end of the file; that is
new information is automatically amended to the end.
·
‘r+’
– Special read and write mode, which is used to handle both actions when
working with a file.
file = open(“file-name”,”w”)
print (file)
This opens the file named “file-name” in writing mode so
that we can make changes to it. The current information stored within the file
is displayed .
Create a text file
Create a file,give it’s name and leave it blank.
We are giving this file a name “file.txt”.
To manipulate the file, write the following in your Python
environment:-
file =
open(“file.txt”,”w”)
file.write(“Write the
file”)
file.write(“text contents add”)
file.close()
In Python, we will see the text what we wrote in program previous.
$ cat file.txt
Write the file
text
contents add
Reading a Text File in Python
We have many ways to read a file by program, whatever we choose for it.
If you need to extract
a string that contains all characters in the file, we will use the following
method: -
file.read()
file = open(“file.text”,
“r”)
print (file.read())
The output of that command will display all the text inside the file.
We could read a
file is to call a certain number of characters.
For example :-
file = open(“file.txt”,
“r”)
print (file.read(5))
The output will be like this :-
Write
If you want to read a file line by line , then you have to use the readline()
function.
We would execute the readline() function for getting the
particular output.
It will return a string of characters that contains a
single line of information from the file.
file = open(“file.txt”,
“r”)
print (file.readline())
This would return the first line of the file, like so: -
Write the file
If we wanted to return only the third line in the file, we would use this:-
file = open(“file.txt”,
“r”)
print file.readline(3)
We read all the lines in the file.You would use the same function, only in a new form. This is called the file.readlines() function.
file = open(“file.txt”,
“r”)
print (file.readlines())
The output you would get from this is: -
[‘Write the file’
,’text contents add’]
Looping over a file object
When you want to see text in again and again in python use :-
file = open(“file.txt”,
“r”)
for i in file:
print (i)
Using the File Write Method
This method is used to add information or content to an
existing file. To start a new line after you write data to the file, you can
add an EOL character.
file = open(“file.txt”,
“w”)
file.write(“text file”)
file.write(“lines.”)
file.close()
Closing a File
When we want to end file you can use the file.close()command to end things.
Apply all modes in one
Opening a text file:-
file = open(“text.txt”, “r”)
Reading a text file: -
file= open(“text.txt”, “r”)
print (file.read())
To read a text file one line at a time:-
file = open(“text.text”,
“r”)
print (file.readline())
To read a list of lines in a text file:-
file = open(“text.txt”,
“r”)
print (file.readlines())
To write new content or text to a file:-
file =open(“text.txt”,
“w”)
file.write(“your text”)
file.close()
You can also use this to write multiple lines to a file at
once:-
file =
open(“text.txt”,”w”)
text
= [“a”, “text”, “for you”]
file.writelines(text)
file.close()
To append a file:-
file = open(“text.txt”,
“a”)
file.write(“Hello World”)
file.close()
To close a file completely when you are done:-
file = open(“text.txt”,
“r”)
print (file.read())
file.close()
0 Comments