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