在python中向后读取n行

时间:2017-03-24 05:23:40

标签: python

我有一个包含5行的文本文件。

this is line 1.
this is line 2.
this is line 3.
this is line 4.
this is line 5.

1。我想以反向顺序打印所有行。即

this is line 5.
this is line 4.
this is line 3.
this is line 2.
this is line 1.
  1. 我想以随机顺序打印行。
  2. 我正在尝试

    import string
    import random
    
    def readingLinesBackwards(filename):
        inputFile = open(test.txt, 'r')
    
        newFileName = "linesBackwards_" + poemFileName
        outputFile = open(newFileName.txt, 'w')
        inputFile.readline()
        for nextLine in inputFile:
            #nextLine = nextLine.strip()
            allLines.append(nextLine)
    
        # close the input (original) file
        inputFile.close()
    
        # now reverse the lines in the list
        allLines.reverse()
        for line in allLines:
            outputFile.write(line)
        # end of for loop
    
        print("\t" + newFileName +" created.\n")
    
        outputFile.close()
        return None
    

    我不确定.reverse()是否有效 有没有办法让线条随机化?

4 个答案:

答案 0 :(得分:2)

以相反的顺序输出行:

# take the lines from the input file and put them into a list
inputFile = open("input.txt","r")
lines = inputFile.readlines()
inputFile.close()

# reverse the list of lines
lines.reverse()

# write the reversed lines into the output file
outputFile = open("output.txt","w")
for line in lines:
    outputFile.write(line)
outputFile.close()

答案 1 :(得分:2)

评论和帮助内联如下。

import random
import os.path

# consolidate common code even for simple apps
def write_lines_to_file(filename, lines):
    with open(filename, 'w') as output:
        output.writelines(lines)
    # Use format strings
    # Hint: print() appends a newline by default. The '\n'
    #       here is a second one.
    print("\t{} created.\n".format(filename))

def do_backwards_and_reverse(filename):
    # Use with to automatically close files...
    with open(filename) as input:
        # readlines(), i.e. no need to read line by line
        lines = input.readlines()

    # for completeness since you're modifying the filename,
    # check to see if there are any path components
    dirname, basename = os.path.split(filename)

    # how to put a path back together
    new_filename = os.path.join(dirname, "lines_backwards_" + basename)
    # the reversed() builtin returns a new reversed list
    # consolidating common code into a re-usable function is a
    # good idea even for simple code like this
    write_lines_to_file(new_filename, reversed(lines))

    new_filename = os.path.join(dirname, "lines_and_words_backwards_" + basename)
    # Create a temporary function (using the lambda keyword) that takes
    # an argument, line, splits it into pieces by whitespace, reverses the
    # pieces, joins them back together with a single space between, and
    # finally appends a newline.
    reverse_words_in_line = lambda line: ' '.join(reversed(line.split())) + '\n'
    # Create a generator (like a list, but faster) of lines in reverse
    # order with each line's words in reverse order.
    altered_lines = (reverse_words_in_line(line) for line in reversed(lines))
    # Pass the generator because almost everything in Python that
    # takes a list is really built to take anything that can be iterated
    write_lines_to_file(new_filename, altered_lines)

    new_filename = os.path.join(dirname, "lines_randomized_" + basename)
    # randomly shuffle a list inplace... which means this has to come
    # last because unlike above where we return new modified lists,
    # shuffle() modifies the list of lines itself. If we want the
    # original order back, we'll have to re-read the original file.
    random.shuffle(lines)
    write_lines_to_file(new_filename, lines)

答案 2 :(得分:1)

以随机顺序打印, 你可以用

import random

list = inputFile.readlines().splitlines()
randlist = list
random.shuffle(randlist)

for line in randlist:
    print line

#for reverse
for line in list.reverse():
    print line

答案 3 :(得分:0)

首先阅读使用readlines()创建行列表的所有行。要以相反的顺序获取线条,请使用切片作为[::-1]。使用join()将所有这些行重新组合成一个字符串并将其写入backwards.txt。最后使用Python的random.shuffle()随机更改行列表的顺序,然后将这些行连接并写入另一个文件。通过使用with,可确保文件全部自动关闭(因此您无需添加close())。

import random    

with open('input.txt') as f_input:
    lines = f_input.readlines()

with open('backwards.txt', 'w') as f_backwards:
    f_backwards.write(''.join(lines[::-1]))

with open('random.txt', 'w') as f_random:
    random.shuffle(lines)
    f_random.write(''.join(lines))

如果您只想打印,请替换为:

print ''.join(lines[::-1])