0

I have a text file with several lines of text which comes from an MS Excel file saved as tab-delimited text.

Two example lines from this file:

BARCODE_01\t@\tA\tW\tE\tS\tO\tM\tE  
BARCODE_02\t@\tM\tI\tR\tA\tC\tL\tE

I need open this file, reformat each line and save it to a new text file. After formatting, the example lines read as:

BARCODE_01
AWESOME

BARCODE_02
MIRACLE

I use "with open..." to open a file and "with open..." to save a file, now I'm confused using both operations. Should I use "nested" "with open" sentences?

This is what I tried:

def formatting_function(line):
    print(">","".join(line.split()).split("@")[0])
    print("".join(line.split()).split("@")[1])

file1 = open('input_file.txt', 'r')
linelist = file1.readlines()
file1.close()

file2 = open('output_file.txt', 'w')

for line in linelist:
    mytext = formatting_function(line)
    file2.write(mytext)

The formatting function do the job when I use it interactively in console, my problem is writing to a file. I got this error with the code above: TypeError: write() argument must be str, not None

mkrieger1
  • 19,194
  • 5
  • 54
  • 65

1 Answers1

0

Your formatting function only prints to console and doesnt return a string.

Assuming everything else is correct (I didn't check in detail yet):

def formatting_function(line):
    result = ">","".join(line.split()).split("@")[0] + "\n"
    result += "".join(line.split()).split("@")[1] + "\n"
    return result

file1 = open('input_file.txt', 'r')
linelist = file1.readlines()
file1.close()

file2 = open('output_file.txt', 'w')

for line in linelist:
    mytext = formatting_function(line)
    file2.write(mytext)

Here is how I would generally rewrite the code:

def formatting_function(line):
    # split line into parts before and after @
    barcode, rest = tuple(line.split("@"))
    # for the part after @: remove all tabs (\t)
    rest = rest.replace("\t", "")
    # concatenate with linebreaks and return as string
    return barcode + "\n" + rest + "\n"

with open('input_file.txt', 'r') as file1:
    linelist = [line.rstrip() for line in file1]

with open('output_file.txt', 'w') as file2:
    for line in linelist:
        mytext = formatting_function(line)
        file2.write(mytext)
ewz93
  • 2,444
  • 1
  • 4
  • 12