Python:提取部分字符串以某种方式被推到新行

Python: Extract parts of a string somehow got pushed down to a new line

我使用此代码提取 html 的最后一个“/”之后的部分。我想在 link 本身之后有那个分区,用逗号分隔。但是,在输出文件中,分区总是被下推到一个新行,而不是连续附加到关联的 link 行。

 with open('links_parts.txt', mode='wt') as outfile:
   for link in file_to_set('links.txt'):
     path_parts = link.rpartition('/')[2]
     outfile.write(link + ','+ path_parts + '\n')

那是因为 link 是一行,因此有一个尾随换行符,您需要使用 str.rstrip:

将其删除
for link in file_to_set('links.txt'):
    link = link.rstrip()
    path_parts = link.rpartition('/')[2]
    outfile.write(link + ',' + path_parts + '\n')