$ 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',
$
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')
3条答案
按热度按时间nwo49xxi1#
在python中执行这项任务是一种非传统的方法,但是如果您只想使用最少的stantard libs行,那么您可以使用
inputfile
具体如下:hi3rlvi22#
你可以这样做
ih99xse13#
我会这样做:-
另一种也包括写入另一个文件的技术可能如下所示:-