Python:为什么每次修改值后都会出现新行?

2024-10-01 13:40:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我对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语言中忽略新行的情况不同。


Tags: 文件inwithitemsangeldevilpeshogosho
2条回答

解决方案如下:

path = "file1"
path2 = "file2"

items = dict()

with open(path) as f:
   content = f.readlines()
   for line in content:
       splitStuff = line.split('!')
       if splitStuff[0] in items:
           items[splitStuff[0]] += ',' + splitStuff[1][:-1]
       else:
           items[splitStuff[0]] = splitStuff[1][:-1]
f.close()

with open(path2, 'a') as f:
   for key, value in items.items():
       f.write(key + '!' + value)
       f.write("\n")

f.close()

您只需通过添加[:-1]从文件的每一行中删除换行符

readlines()读取的行后面有一个换行符

for line in content:
    line = line.rstrip()   
    splitStuff = line.split('!')
    ... etc ...

相关问题 更多 >