DataGuy DataGuy - 10 days ago 7
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:

windfall
winnable
winner
winners
winning


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

windfall|winnable|winner|winners|winning


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

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 |.