我对python还很陌生,我正在尝试各种各样的小东西来看看它们是如何工作的:
items = dict()
with open(path) as f:
content = f.readlines()
for line in content:
splitStuff = line.split('!')
if splitStuff[0] in item:
items[splitStuff[0]] += ',' + Results[1]
else:
items[splitStuff[0]] = Results[1]
f.close()
with open(path2, 'a') as f:
for key, value in items.items():
f.write(key + '!' + value)
f.close()
它打开一个包含以下内容的文件:
3!Angel
3!Devil
4!Nasko
4!Pesho
4!Gosho
5!Kalin
6!Gancho
6!Boncho
6!Toncho
6!Moncho
最后写了一个包含以下内容的文件:
3!Angel
,Devil
4!Nasko
,Pesho
,Gosho
5!Kalin
6!Gancho
,Boncho
,Toncho
,Moncho
我不明白的是,每次我编辑一个值时,那些新行在哪里出现
编辑:这是所需的输出
3!Angel,Devil
4!Nasko,Pesho,Gosho
5!Kalin
6!Gancho,Boncho,Toncho,Moncho
EDIT2:算了吧。这是因为在原始文件中有新行,而且在python中逐行读取文件显然也会捕获新行,这与c语言中忽略新行的情况不同。
解决方案如下:
您只需通过添加
[:-1]
从文件的每一行中删除换行符用
readlines()
读取的行后面有一个换行符相关问题 更多 >
编程相关推荐