[英]How to display number of lines in a file python
我假設我有一個包含許多行的文本文件,例如:
fsdfgsfgf
b3cbc3b45
456346aaa
bce45fa45
我想顯示每一行及其編號:
text_file = open(r'C:\\Users\\user\\Text.txt', 'r')
for a in Plaintxt_file:
text=a[0:9]
print ('Text:', text )
print('it is number is:', a)
我想要的結果是:
Text: b3cbc3b45
it is number is:2
但是我的結果是:
Text: b3cbc3b45
it is number is:b3cbc3b45
那么如何在python中顯示文件的行數呢?
# with open(filename) as file:
# for index, line in enumerate(file,1)
file = ['fsdfgsfgf','b3cbc3b45','456346aaa','bce45fa45']
for index, line in enumerate(file,1):
print ('Text:', line )
print('it is number is:', index)
出:
Text: fsdfgsfgf
it is number is: 1
Text: b3cbc3b45
it is number is: 2
Text: 456346aaa
it is number is: 3
Text: bce45fa45
it is number is: 4
您可以將enumerate
命令與readlines()
方法一起使用,如下所示:
f = open('test.txt', 'r')
for index, line in enumerate(f.readlines()):
# index represents the index of the line and line the line in the file.
使用with
打開文件, enumerate
顯示的行數。
with open('test.txt') as f:
for index, line in enumerate(f, 1):
print 'Text:', line,
print 'Its number is:', index
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.