简体   繁体   English

如何跳过行,直到在txt文件中找到“关键字”并将其余内容另存为csv? 蟒蛇

[英]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 ,然后使用seekwritelines

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.

相关问题 Python:如何在文本文件中查找关键字,在该关键字左侧保存 60 个字符,循环直到文本文件结束 - 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 我们如何在 excel 和 csv 文件中自动跳过行,直到 header 行在 Z23EEEB4347BDD26BFCDDpyB7EE9 中找到 - How can we skip lines automatically in excel and csv file until header row is found in python (pyspark) 读取csv行并将其另存为单独的txt文件,命名为行-python - Read csv lines and save it as seperate txt file, named as a line - python 如何保留从a.csv文件中删除第二列并将文件的rest保存到Python中的a.txt文件 - How to keep the remove the second column from a .csv file and save the rest of the file to a .txt file in Python 使用python脚本阅读时如何跳过csv文件中的空行? - How to skip empty lines in csv file when reading with python script? python-跳过CSV文件的顶行 - python - skip top lines of CSV file 如何使用Python跳过文件中的2行? - How to skip 2 lines in a file with Python? 如果在PYthon中满足条件,则跳过行直到文本文件中的下一个块 - Skip lines until the next block in a text file if a condition is met in PYthon 如何在Python中将JSON字符串保存为CSV或TXT? - How to save JSON string into CSV or TXT in Python? 如何使用关键字从txt文件搜索和检索整行 - How to search and retrieve whole lines from a txt file using Keyword
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM