如何用python读取文本中指定行的内容
答案:1 悬赏:0 手机版
解决时间 2021-01-11 10:31
- 提问者网友:皆是孤独
- 2021-01-11 06:56
如何用python读取文本中指定行的内容
最佳答案
- 五星知识达人网友:上分大魔王
- 2021-01-11 07:46
1 利用python的readlines()函数:
[python] view plain copy
fobj = open(r'Ori.Data.txt','r')
for line in fobj.readlines()[1000:]
fobj.close()
2 利用 linecache
[python] view plain copy
import linecache
print(linecache.getline(r'D:\z.txt',10))
3 读取10行到13行中的内容
[python] view plain copy
lnum = 0
with open('pit.txt', 'r') as fd:
for line in fd:
lnum += 1;
if (lnum >= 10) && (lnum <= 13):
print line
fd.close()
4 求文本的行数
[python] view plain copy
fobj = open('Ori_Data.txt','r')
row_len = len(fobj.readlines())
[python] view plain copy
[python] view plain copy
fobj = open(filepath,'r')
data = fobj.read()
fobj.close()
text_len = data.count('\n')
[python] view plain copy
fobj = open(r'Ori.Data.txt','r')
for line in fobj.readlines()[1000:]
fobj.close()
2 利用 linecache
[python] view plain copy
import linecache
print(linecache.getline(r'D:\z.txt',10))
3 读取10行到13行中的内容
[python] view plain copy
lnum = 0
with open('pit.txt', 'r') as fd:
for line in fd:
lnum += 1;
if (lnum >= 10) && (lnum <= 13):
print line
fd.close()
4 求文本的行数
[python] view plain copy
fobj = open('Ori_Data.txt','r')
row_len = len(fobj.readlines())
[python] view plain copy
[python] view plain copy
fobj = open(filepath,'r')
data = fobj.read()
fobj.close()
text_len = data.count('\n')
我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息
大家都在看
推荐资讯