Shubham R
Shubham R

Reputation: 7644

Read n lines from the end backward in python

i have a text file which contains 5 lines.

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

1. i want to print all the lines in backward order. i.e

this is line 5.
this is line 4.
this is line 3.
this is line 2.
this is line 1.
  1. i want to print lines in random order.

i was trying

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

I am not sure if .reverse() will work Is there any way to randomize the lines ?

Upvotes: 0

Views: 1101

Answers (4)

Martin Evans
Martin Evans

Reputation: 46779

First read all of your lines in using readlines() to create a list of lines. To get the lines in reversed order, use a slice as [::-1]. Use join() to join all these lines back together into a single string and write it to backwards.txt. Finally use Python's random.shuffle() to randomly change the order of your list of lines, and then join and write these to another file. By using with, it ensures the files are all closed automatically (so you don't need to add 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))

If you just want to print, then replace with something like:

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

Upvotes: 0

Harvey
Harvey

Reputation: 5821

Comments and help inline below.

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)

Upvotes: 2

Akshay Apte
Akshay Apte

Reputation: 1653

for printing in random order, you can use

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

Upvotes: 1

nfriesen
nfriesen

Reputation: 31

To output the lines in reverse order:

# 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()

Upvotes: 2

Related Questions