python 获取 文本 行号
时间: 2023-10-16 11:27:14 浏览: 149
要获取文本中某一行的行号,可以使用Python的文件对象的readlines()方法来读取文件中的所有行,然后遍历这些行,找到所需的行,记录行号即可。
例如,假设我们要获取文件中第5行的行号,可以使用以下代码:
```python
filename = "example.txt"
target_line = 5
with open(filename, "r") as f:
lines = f.readlines()
for i, line in enumerate(lines):
if i == target_line - 1:
print("Line {} is: {}".format(target_line, line))
```
这里首先使用with关键字打开文件,并使用readlines()方法读取所有行。接着使用enumerate()函数遍历所有行,每次迭代时记录当前行号i和行内容line。当行号等于目标行号减1时,即找到了目标行,输出行号和行内容。注意,这里的行号从1开始计数,而不是从0开始。
相关问题
python 读取文本文件的行号及行内容_Python-从文本文件中查找行号
可以使用Python内置的文件操作函数来读取文本文件的行号和行内容。以下是一个简单的示例代码:
```python
with open('filename.txt', 'r') as file:
for idx, line in enumerate(file):
print("Line {}: {}".format(idx, line.strip()))
```
这个代码打开一个名为`filename.txt`的文本文件并逐行读取其内容。`enumerate`函数可以同时返回行号和行内容,`strip`函数可以去除行末的空白字符。最终输出的结果是每一行的行号和行内容,例如:
```
Line 0: This is the first line.
Line 1: This is the second line.
Line 2: This is the third line.
```
python按照行号读取txt
你可以使用以下代码按行号读取文本文件:
```python
def read_line_by_number(file_path, line_number):
with open(file_path, 'r') as file:
lines = file.readlines()
if line_number <= len(lines):
return lines[line_number - 1]
else:
return None
file_path = 'path/to/your/file.txt'
line_number = 5
line = read_line_by_number(file_path, line_number)
if line:
print(line)
else:
print('Line number {} does not exist in the file.'.format(line_number))
```
在上面的代码中,`file_path` 是你要读取的文本文件的路径。`line_number` 是你想要读取的行号。`read_line_by_number` 函数将会返回指定行号的文本行,如果该行不存在则返回 `None`。你可以根据需要调整文件路径和行号来使用该函数。