我有多个.txt文件(O1test、O2test、O3test、O4test)
text of 01test(hello,my,friend,sorry,newbie)
text of 02test(hello,my,friend,sorry,newbie)
text of 03test(hello,my,friend,sorry,noob)
text of 04test(hello,my,friend,sorry,amatuer)输出txt文件可能如下所示
Newbie
01test
02test
Noob
O3test
Amatuer
O4test正如您所看到的,我需要写一个文件名和第XX行文本,然后再写一个文件名和第XX行文本,但是如果第xxth和前面的行相同,那么接下来再写。
我试过了但现在我被困住了。
import os
for root, dirs, files in os.walk("C:\\Users\\42077\\Desktop\\test\\"):
for file in files:
if file.endswith(".txt"):
with open("C:\\Users\\42077\\Desktop\\test\\!output.txt", "a") as f: as f
f.write(os.path.join( file)+"\n")发布于 2021-02-21 12:40:21
如何读取第五行:打开文件,在数行的同时循环这些行;到达第五行时停止。
def get_nth(filename, n):
"""
Return the nth line from filename
"""
with open(filename) as lines:
for idx, line in enumerate(lines, 1):
if idx == n:
return line.rstrip('\n')
raise ValueError('file %s only has %i lines' % (filename, idx))如果文件有更少的行,应该发生什么?我决定提出一个错误,但不同的设计当然是可能的。
若要组织一组值及其所在文件的结果,请使用列表的dict;
import glob
from collections import defaultdict
where = defaultdict(list)
for filename in glob.glob('*test'):
where[get_nth(filename, 5)].append(filename)循环遍历生成的dict并打印结果应该是相当明显的;我将此作为练习。
https://stackoverflow.com/questions/66302257
复制相似问题