从文本文件导入Python中的特定行

时间:2015-02-17 00:26:55

标签: python

我是Python的新手。 我有一个源文件,其中有10行。 使用Python我想将1个特定行导入新文件。

请告诉我如何处理此事。

3 个答案:

答案 0 :(得分:2)

如果您知道之后的行数,可以使用linecache

import linecache
a_line = linecache.getline('/tmp/file.txt', 4)

# save it to new file
with open('new_file.txt', 'w') as f:
          f.write(a_line)

答案 1 :(得分:1)

你可以写一个“for”循环来逐行计数,直到你想要的那一行。之后,将该行的副本保存到变量中,在本例中为“stringTemp”:

with open("file.txt", "r") as inputStream: # open a file.txt onto a stream variable
stringTemp = ""  # initialize an empty string, where you'll save the line you want
particularLineNumber = 3
count = 0      # a variable to keep count of which line you are on
for line in inputStream:   # "for each thing in the stream variable, save it onto "line"
    if count == particularLineNumber - 1: # if we are on the line we want...
        stringTemp = line                 # ... save it to stringTemp
    count = count + 1         # if we are NOT on the line we want, increase the counter


# ... write the variable stringTemp onto another file ...  

我假设您希望您的行号为“1,2,3,4,...,9,10”。如果您决定从0开始(“0,1,2,3 ... 10”),则删除“if count == specialLineNumber - 1”上的“ - 1”

答案 2 :(得分:1)

这将立即读取整个文件:

with open(fname) as f:
    content = f.readlines()

读完所有行后,你可以用它做任何你想做的事。

这将一次读取一行文件:

with open(fname) as f:
    for line in f:
        <do something with line>

但这已被多次回答:

How to read large file, line by line in python

How do I read a file line-by-line into a list?