![](/img/trans.png)
[英]Python: how to find a keyword in a text file, save 60 characters to the left of that keyword, loop until end of text file
[英]How to skip lines until find the 'keyword' in txt file and save rest as csv? python
我有一个csv格式的txt文件,但顶部没有多余的几行。 在“ [App]”行之后,我需要跳过几行8-10行(取决于文件)。
该文件如下所示:
1, trash
2, trash
3, [APP]
4
.
.
.
100
我需要将4-100行保存为csv,其中4将是标题,其余是行。
什么是最好的方法? 我尝试了一个:“打开”
with open('som.txt', 'r') as fin:
data = fin.read().splitlines(True)
with open('som.txt', 'w') as fout:
fout.writelines(data[7:])
print(data)
因此,我现在有了数据列表及其确定的内容,但是该代码跳过了几行而不是特定单词之后的几行。 另外,我无法将此列表另存为正确的CSV文件; c您能帮忙吗?
使用readlines
,然后使用seek
和writelines
:
with open('some.txt', 'r+') as f:
text=f.readlines()
f.seek(0)
f.writelines(text[[i for i, s in enumerate(mylist) if '[APP]' in s][0]:])
现在,您的文件将按预期运行,另外还有一个优点是它没有按索引运行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.