[英]How to skip lines until find the 'keyword' in txt file and save rest as csv? python
I have a txt file in csv form but with unnecessary few lines on top. 我有一个csv格式的txt文件,但顶部没有多余的几行。 I need to skip a few 8-10 lines (it depends from file), after "[App]" line.
在“ [App]”行之后,我需要跳过几行8-10行(取决于文件)。
The file looks like this: 该文件如下所示:
1, trash
2, trash
3, [APP]
4
.
.
.
100
and I need to save the 4-100 lines as csv where 4 will be headers and rest are rows. 我需要将4-100行保存为csv,其中4将是标题,其余是行。
What is the best way? 什么是最好的方法? I tried a: "with open"
我尝试了一个:“打开”
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)
So, I have now data list and its ok, but that code skip lines after a number of lines, not specific word. 因此,我现在有了数据列表及其确定的内容,但是该代码跳过了几行而不是特定单词之后的几行。 Also, I can't save this list as properly CSV file;
另外,我无法将此列表另存为正确的CSV文件; c Can u help?:)
c您能帮忙吗?
Use readlines
, then use seek
, and writelines
: 使用
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]:])
Your file will be now as expected, and another plus that it doesn't do it by index. 现在,您的文件将按预期运行,另外还有一个优点是它没有按索引运行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.