在python中自动设置文本格式

iezvtpos  于 2021-09-29  发布在  Java
关注(0)|答案(3)|浏览(354)

我有一个txt文件,包含每行的国家代码列表。格式如下:

AL
DZ
AS
AO
AI
BS
BB
BY
BJ
BA

我想使用python格式化文本,为每个国家/地区代码添加引号,后跟逗号。

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

nwo49xxi1#

在python中执行这项任务是一种非传统的方法,但是如果您只想使用最少的stantard libs行,那么您可以使用 inputfile 具体如下:

$ 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',
$
hi3rlvi2

hi3rlvi22#

你可以这样做

with open('untitled.txt', 'r') as file:
    output =[]
    for l in file:
        output.append("'"+l.strip()+"',\n")
ih99xse1

ih99xse13#

我会这样做:-

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

另一种也包括写入另一个文件的技术可能如下所示:-

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')

相关问题