简体   繁体   English

如何从python的输入文件中选择特定行

[英]How do I choose a specific line from a input file in python

Suppose I have a input Verilog file shown below: 假设我有一个输入Verilog文件,如下所示:

module c17 (N1,N2,N3,N6,N7,N22,N23);
input N1,N2,N3,N6,N7;
output N22,N23;
wire N10,N11,N16,N19;
NAND2X1 NAND2_1 (.Y(N10),.A(N1),.B(N3));
NAND2X1 NAND2_2 (.Y(N11),.A(N3),.B(N6));
NAND2X1 NAND2_3 (.Y(N16),.A(N2),.B(N11));
NAND2X1 NAND2_4 (.Y(N19),.A(N11),.B(N7));
NAND2X1 NAND2_5 (.Y(N22),.A(N10),.B(N16));
NAND2X1 NAND2_6 (.Y(N23),.A(N16),.B(N19));

How do I start reading the file directly from the 5th line onwards where the string starts from NAND2x1 我如何直接从字符串从NAND2x1开始的第5行开始直接读取文件

You're going to want to use the linecache module. 您将要使用linecache模块。

https://docs.python.org/2/library/linecache.html https://docs.python.org/2/library/linecache.html

So: 所以:

import linecache

line = linecache.getline('myfile.txt', 5)

You don't have to open the file as with open() . 您不必像open()一样open()文件。

You can read() the file into a list and slice it, for example: 您可以将文件read()list并将其slice ,例如:

with open(file, 'r') as f:
    data = f.read().splitlines()[4:]
    for line in data:
       # your code

You can also use f.readlines() but then you will have to use .rstrip() when processing each line to remove new line character. 您也可以使用f.readlines()但是在处理每行以删除换行符时,必须使用.rstrip()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从 python 中的文本文件中删除特定行 - How do I remove a specific line from a text file in python 我如何使python在文件的第一行之后随机选择一行? - How do i make python choose randomly one line after the first line of a file? 如何允许Python从2个文本文件(同一行)中选择一条随机行,然后将其存储为变量? - How do I allow Python to choose a random line from 2 text files (that are the same line) and then store them as variables? 如何执行以特定代码行开头的python文件? - How do I execute a python file beginning in a specific code line? 如何使用 Python 覆盖 CSV 文件中的特定行 - How do I overwrite a specific line in a CSV file with Python 如何从gui中收到的多行输入写入python文件? - How do I write to a python file from a multi-line input received in a gui? 我如何使用文本文件中的一行作为python中的函数输入? - how do i use a line from a text file as a function input in python? 如何使用python从列表中选择特定项目并保存在新列表中 - how do I choose specific items from a list using python and save in a new list 如何从Python中的特定文本行中提取文本? - How do I pull text from a specific text line in Python? 如何从 python 中的 txt 文件中选择要打印的行 - How to choose what line to print from a txt file in python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM