Python read file in linux

How to Read a File in Python

You have seen various types of data holders before: integers, strings, lists. But so far, we have not discussed how to read or write files.

Read file

The Python programming language provides the ability to work with files using open() .

Python programming treats some files as text files, where lines are separated by newline characters \n . You can open regular files with the paramater r .

Other files are considered binary and can be handled in a way that is similar to the C programming language. They need to be opened with the parameters rb .

read file into string

This is a sample program that shows how to read data from a file.

The file needs to be in the same directory as the program, if not you need to specify a path.

Create python script. Open editor of your choice and create new python script. Then paste the following code.

f = open(«file.txt»,«r»)
lines = f.readlines()
print(lines)

The read method readlines() reads all the contents of a file into a string.

Save the file with name example.py and run it.

read file line by line

To output line by line, you can use a for loop. The lines may include a new line character \n , that is why you can output using endl=»» .

f = open(«filename.txt»,«r»)
lines = f.readlines()

for line in lines:
print(line, end=«»)

Another option is to remove the newline characters with the replace() method.

f = open(«test.py»,«r»)
lines = f.readlines()

for line in lines:
line = line.replace(«\n»,«»)
print(line)

read file with keyword

The with keyword can be used to read files too. This automatically closes your file.

#!/usr/bin/env python

# Define a filename.
filename = «bestand.py»

# Open the file as f.
# The function readlines() reads the file.
with open(filename) as f:
content = f.readlines()

# Show the file contents line by line.
# We added the comma to print single newlines and not double newlines.
# This is because the lines contain the newline character ‘\n’.
for line in content:
print(line),

The first part of the code will read the file content. All of the lines read will be stored in the variable content. The second part will iterate over every line in the variable contents.

Читайте также:  Linux usb подключить флешку

If you do not want to read the newline characters ‘\n’, you can change the statement f.readlines() to this:

#!/usr/bin/env python

# Define a filename.
filename = «bestand.py»

# Open the file as f.
# The function readlines() reads the file.
with open(filename) as f:
content = f.read().splitlines()

# Show the file contents line by line.
# We added the comma to print single newlines and not double newlines.
# This is because the lines contain the newline character ‘\n’.
for line in content:
print(line)

While the codes above work, we should always test if the file we want to open exists. We will test first if the file does not exist, if it does it will read the file else return an error. As in the code below:

#!/usr/bin/env python
import os.path

# Define a filename.
filename = «bestand.py»

if not os.path.isfile(filename):
print(‘File does not exist.’)
else:
# Open the file as f.
# The function readlines() reads the file.
with open(filename) as f:
content = f.read().splitlines()

# Show the file contents line by line.
# We added the comma to print single newlines and not double newlines.
# This is because the lines contain the newline character ‘\n’.
for line in content:
print(line)

If you are new to Python programming, I highly recommend this book.

Источник

How to read and write to files in Python

Files are used to store any data permanently for future use. Reading from a file and writing to a file are common requirements for any programming language. Any file needs to open before reading or writing. Most of the programming languages use open() method to open a file for reading or writing using file object. Different types of file access mode can be used as an argument of open() method to mention the purpose of opening the file. This argument is optional. close() method is used after completing the file operation to release the resources occupied by the file object. Two types of files can be handled by Python programming. These are text file and a binary file. How to read and write text files in Python programming is described in this tutorial.

File Access Modes:

It is mentioned before that different types of file access modes can be used in open() method and these are described in this part. Commonly used modes are mentioned below.

Mode Purpose
t It indicates a text file and it is the default file type.
b It indicates a binary file.
r It opens the file for reading and it is the default mode for opening any file.
w It opens the file for writing.
x It opens the file for writing if not exists.
a It opens the file for adding content at the end of the file if the file exists, otherwise, create the file and add the content in the beginning.
r+ It opens the file for reading and writing and places the cursor at the beginning of the file. It raises an error if the file does not exist.
w+ It opens the files for reading and writing and overwrites the data if the file already exists.
a+ It opens the file for reading and writing and places the cursor at the end of the file for the existing file. It creates the file if it does not exist.
Читайте также:  Linux графические оболочки mate

Methods:

Many methods exist in Python to read or write the file. The most commonly used methods are mentioned here.

This method contains two arguments. The first argument is mandatory that is used to take the filename for reading or writing. The second argument is optional that is used to set the file access mode. Te default file access mode is ‘rt’. The return type of this method is a file object that is used for reading and writing the file.

This method is used to close the file and make it available for another purpose. After calling this method, the file handler object will be unusable.

This method is used to read a specific amount of bytes from a file using a file object.

This method is used to read a particular line from a file using a file object.

This method is used to read all lines of a file separated by comma(,) using file object.

This method is used to write content into a file using a file object.

Reading Text File:

Create a text file named ‘countryList.txt’ with the following content to use it in the next part of the article.

Example 1: Reading file using read(), readline() and readlines()

Create a file named read1.py with the following python script. It will read the file based on the byte size using read(), read the fixed number of characters from a file using readline() and read all lines of a file in an array using readlines().

# Open file for reading
FileHandler = open ( «countryList.txt» , «r» )

# Read file content based on size
print ( ‘Output from read() method \n ‘ , FileHandler. read ( 2048 ) )

# Close the file
FileHandler. close ( )

# Open file for reading and writing
FileHandler = open ( «countryList.txt» , «r+» )

# Read the file content of third line
print ( ‘Output from readline() method \n ‘ , FileHandler. readline ( 5 ) )

# Close the file
FileHandler. close ( )

# Open file for reading and appending
FileHandler = open ( «countryList.txt» , «r» )

# Read all content of the file
print ( ‘Output from readlines() method \n ‘ , FileHandler. readlines ( ) )

Читайте также:  Alpine linux virtualbox install

# Close the file
FileHandler. close ( )

The following output will appear after running the script.

Example 2: Reading file line by line using a loop

Create a file named read2.py with the following script. It will read and print each line of the file from fileObject using for loop.

# Open file for reading
fileObject = open ( «countryList.txt» , «r» )

# Read a file line by line and print in the terminal
for line in fileObject:
print ( line )

The following output will appear after running the script.

Example 3: Reading file by using with the statement

Create a file named read3.py with the following script. It will read the file without any file object by using the statement.

# Read file using with the statement

with open ( «countryList.txt» ) as fhandler:
print ( fhandler. readlines ( ) )

The following output will appear after running the script.

Writing Text File:

The content can be written in a file by defining the file object or by using with the statement.

Example 4: Writing to a file using file object

Create a file named write1.py with the following script. It will open a text file for writing and write three lines using write() method.

# Open file for writing
fileObject = open ( «newfile.txt» , «w» )

# Add some text
fileObject. write ( «Text for first line \n » )
fileObject. write ( «Text for second line \n » )
fileObject. write ( «Text for third line \n » )

# Close the file
fileObject. close ( )

Run the script and check the file is created with the content or not. The following output will appear after running the script and running the ‘cat’ command.

Example 5: Writing to a file using with the statement

The content can be written to a file without defining file object. Create a file named write2.py with the following script. It will write two lines in to file by using with statement.

# Open file for writing using with statement

with open ( «myfile.txt» , ‘w’ ) as fileObj:
fileObj. write ( «First Line \n » )
fileObj. write ( «Second Line \n » )

The following output will appear after running the script and ‘cat’ command to read the file.

Conclusion:

Mostly used methods to read content from a file and write content to a file in python are described in this tutorial by using very simple examples. The new python users will be able to know the uses of necessary functions for reading or writing files.ch

About the author

Fahmida Yesmin

I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.

Источник

Оцените статью
Adblock
detector