Home > Backend Development > Python Tutorial > How to use the fileinput module for file iteration in Python 2.x

How to use the fileinput module for file iteration in Python 2.x

PHPz
Release: 2023-08-02 11:53:06
Original
1386 people have browsed it

How to use the fileinput module for file iteration in Python 2.x

Overview:
In Python programming, processing files is a common task. Python's fileinput module provides a convenient way to iteratively process text files. It allows us to iterate through each line in the file to perform the necessary operations. This article will introduce how to use the fileinput module for file iteration in Python 2.x version, and further explain it through code examples.

Basic usage of the fileinput module:
First, we need to import the fileinput module. Then, you can use the fileinput.input() function to create a file iterator. This function accepts an iterable list of file names as argument and returns an iterator object. We can use this iterator object in a for loop to iterate through each line of the file. In the loop, you can use other functions and methods provided by the fileinput module to obtain the current line, current file name and other related information.

The following is a simple example that shows how to use the fileinput module to iterate through each line in a file and print the content and current file name of each line:

import fileinput

# 遍历文件的每一行
for line in fileinput.input(['file.txt']):
    # 打印当前行的内容和当前文件名
    print(line.rstrip(), fileinput.filename())

# 打印总行数
print('Total lines:', fileinput.lineno())
Copy after login

In the above example, we Through fileinput.input(['file.txt']), a file iterator is created to iteratively process the text file named 'file.txt'. line.rstrip()Can remove the newline character at the end of the line, fileinput.filename()Returns the current file name. fileinput.lineno()Returns the number of lines that have been read in the file.

Other common methods and functions of the fileinput module:
In addition to the basic iteration function, the fileinput module also provides some other functions to help us process files more conveniently.

  1. fileinput.isfirstline(): Determine whether the current line is the first line of the file.
  2. fileinput.lineno(): Returns the number of lines read.
  3. fileinput.nextfile(): Move to the next file, if it exists.
  4. fileinput.close(): Close the iterator.
  5. fileinput.filename(): Returns the current file name.
  6. fileinput.filelineno(): Returns the current line number.
  7. fileinput.fileno(): Returns the file descriptor of the current file.
  8. fileinput.input(files=None, inplace=False, backup='', mode='r', bufsize=-1, openhook=None): Create a file iterator.

The following is an example that demonstrates how to use the fileinput module to count the number of lines and characters in a file:

import fileinput

line_count = 0
char_count = 0

# 遍历文件的每一行
for line in fileinput.input(['file.txt']):
    # 统计总行数
    line_count += 1
    # 统计总字符数(去除空格和换行符)
    char_count += len(line.strip())

# 打印统计结果
print('Total lines:', line_count)
print('Total characters:', char_count)
Copy after login

The above example will iterate through each line of the file 'file.txt' , count the total number of lines and total characters (removing spaces and newlines). Then print the statistical results.

Conclusion:
Using Python’s fileinput module can easily iteratively process text files. We can flexibly use the functions and methods it provides to operate each line of the file and obtain related file and line information. By learning and using the fileinput module, we can process files more efficiently and improve programming efficiency.

The above is the detailed content of How to use the fileinput module for file iteration in Python 2.x. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template