-2

I have a txt file containing a list of country codes for each line. The format is like this:

AL
DZ
AS
AO
AI
BS
BB
BY
BJ
BA

I would like to format the text using Python, adding quotation marks for each country code, followed by a comma.

'AL',
'DZ',
'AS',
'AO',
'AI'

3 Answers3

0

You can do it like that

with open('untitled.txt', 'r') as file:
    output =[]
    for l in file:
        output.append("'"+l.strip()+"',\n")
Piotr Nowakowski
  • 376
  • 1
  • 11
0

Well, it is an unorthodox way to do that task in python, but if you want to do it with the fewest line only with stantard libs, than you can use the inputfile lib as follows:

$ cat test.txt 
AL
DZ
AS
AO
AI
BS
BB
BY
BJ
BA
$ python3
Python 3.8.10 (default, Jun  2 2021, 10:49:15) 
[GCC 9.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import fileinput
>>> for line in fileinput.input("test.txt", inplace=True):
...     print(line.replace(line, f"'{line.strip()}',"))
... 
>>> 

$ cat test.txt 
'AL',
'DZ',
'AS',
'AO',
'AI',
'BS',
'BB',
'BY',
'BJ',
'BA',
$ 
czeni
  • 427
  • 2
  • 11
0

I would do it like this:-

with open('flat.txt') as txt:
    cc = []
    for line in txt:
        cc.append("'"+line.rstrip('\n')+"'")
    print(',\n'.join(cc))

Another technique that also include writing to another file could look like this:-

with open('flatin.txt') as txtin:
    with open('flatout.txt', 'w') as txtout:
        txtout.write(',\n'.join(
            "'" + line.rstrip('\n') + "'" for line in txtin) + '\n')