2

I have a text input file:

AAA
BBB
CCC
DDD
EEE
FFF,FFF
GGG

I want to copy every kth line of this file into an output text file. For example, for k=2 it would be:

BBB
DDD
FFF FFF

And for k = 3 it should be

CCC
FFF FFF

This is what I have done so far, I am struggling to find how to identify K in the function. Could you please help me?

def ex1 (filen1, filen2, k):
    fp1=open(filen1,'r') #open file to read from
    fp2=open(filen2,'a') #open file to write to
    
    count=1 #number of lines which have been copied
    
    for line in fp1:
        line = next(str(filen1))
        list.append(line.strip())
        fp1.readline
    return list     
fp1.close
fp2.close    
ex1('Input file.txt', 'Output.txt')
5
  • have you explored seek(), next() functions?
    – anurag
    Commented Dec 18, 2020 at 8:54
  • 2
    fp1.close doesn't do anything. To call a function that takes no parameters you still need to say fp1.close(). This isn't ruby. Commented Dec 18, 2020 at 8:56
  • 1
    increment count inside the loop and check if count % k == 0, if it is, append that line to new file Commented Dec 18, 2020 at 8:57
  • What is next(str(filen1)) doing? filen1 is already a str, the name of the file, then you're iterating over it taking the next character, which will be the first in the name. Commented Dec 18, 2020 at 8:58
  • You don't define list anywhere, so you might actually be trying to use the append function defined on the list type. Commented Dec 18, 2020 at 8:59

6 Answers 6

4

You have some trouble in your code to even read the content of the input file. If your files are not extremely big, where you would run into memory problems, you can do it like this. Open the first files and read all the lines into a list, where each entry is a new line. Also try to use the with statement to open the files, because it automatically closes the files again (it's better practice in general).

Then you just do the reverse and write the lines to the other file, however you simly index the lines list so that it starts at the k-1th element and only contains every kth element.

k = 2

with open(filen1, 'r') as input_file:
    lines = input_file.readlines()

with open(filen2, 'w') as output_file:
    for line in lines[k-1::k]:
        output_file.write(line)
2

You could make use of itertools:

import itertools

with open(filen1, 'r') as f:
    lines_of_interest = itertools.islice(f, 0, None, 2) #the last number defines the nth line to slice for

with open(filen2, 'w') as out:
    for item in lines_of_interest:
        out.write("%s\n" % item)
2

You could also do it this way.

def go(k):
    with open("test.txt","r") as file:
        for count, line in enumerate(file):
            if (count+1)%k == 0:
                yield line    

with open("output.txt","w") as output:
    for s in go(2):
        output.write(s)

Output for sample value of k = 2:

BBB
DDD
FFF,FFF
1

You can use a list to store the lines.

Then iterate over this list with a for loop using "k" as step param of the loop

def ex1(filen1, filen2, k):
    fp1=open(filen1,'r') #open file to read from
    fp2=open(filen2,'w') #open file to write to
    
    #Store each line in a list
    tempStorage=[]
    line=fp1.readline()
    while(line):
        tempStorage.append(line)
        line=fp1.readline()
    
    
    #K Value set as STEP 
    for i in range(k-1,len(tempStorage),k):
        fp2.write(tempStorage[i])
    fp1.close()
    fp2.close()  
    
ex1("in.txt","out.txt",2)
1
  • This is unidiomatic on several counts, and has the obvious scalability issue that reading all the files into memory is not feasible for really big input files.
    – tripleee
    Commented Dec 18, 2020 at 11:51
1
def ExtractFile (inputfile, outputfile, position):
    #set the count at 0
    count = 0
    #open both files, one for read and one for write
    inputfile = open(inputfile, "r")
    outputfile = open(outputfile, "w")
    #read lines one by one
    lines = inputfile.readlines()
    for line in lines:
        count += 1 #making sure count tallies with line number
        if count%position == 0: #meaning if the line count is divisible by position without remainder..
            outputfile.write(line)  #then you write the line you want in file
    #close both files in this function
    inputfile.close
    outputfile.close

ExtractFile('input.txt', 'output.txt', 2)

There are comments explaining the code. Also try to use variable names that have context, in that way you can understand better on what you code.

For this code, if your input file is:

A
B
C
D
E
F

Your output file should write as,

B
D
F
0

Here is another approach:

def write_kth_line(k):
    # open files
    input_file = open('./inputFile.txt', 'r')
    output_file = open('./outputFile.txt', 'w')

    # read all lines
    lines = input_file.readlines()
    # iterate over lines with k as the step size
    for i in range(k-1, len(lines), k):
        output_file.write(lines[i])

    # close files
    input_file.close()
    output_file.close()


write_kth_line(3)

For k=2, the output file contains:

BBB
DDD
FFF,FFF

And k=3, results:

CCC
FFF,FFF

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.