DataGuy DataGuy - 9 months ago 61
Python Question

adding character at the end of each string in a file

I have a txt file that contains a single column of single words as such:


I want to use the words in the file as regex strings for a mapping jobs. When finished the words should look like this:


I need to use python or awk to open the file, place a | at the end of each and write the new content to a new file with the new character added and the column converted to a single horizontal line.

any suggestions?

Answer Source

Using Python you could do:

with open('oldfile.txt') as fin:
    with open('newfile.txt', 'w') as fout:
        fout.write('|'.join(map(str.strip, fin)))

The str.split removes newlines and whitespaces, while the join concatenates the lines with |.