修改CSV文件中的URL字符串 - 输出文件包含单个单元格中的每个字符

时间:2014-05-11 19:50:47

标签: python url csv

我正在尝试编写一个允许我从URL中删除某些元素的函数。这些网址存储在名为Backlink_Test的CSV中。我想迭代该URL列表中的每个项目,从URL中删除不需要的元素,然后将修改后的URL添加到新列表中,然后将其存储在名为Cleaned_URLs的新CSV中。

代码正在工作,我可以打开源文件,运行循环,然后将结果存储在目标文件中。但是,我遇到了一个非常令人讨厌的问题:在目标文件中,URL存储,每个字符都存储在单个单元格中,而不是整个网格存储在一个单元格中。

这让我感到惊讶,因为我做了一点测试,我将内容从CSV复制到另一个(没有修改任何内容),并且存储了多个字符的单词。所以我怀疑for循环会产生问题吗?

非常感谢任何帮助/见解!下面的代码,以及附加的目标文件的屏幕截图。

import csv

new_strings = []    

#replace unwanted elements and add cleaned strings to new list
with open("Backlink_Test.csv", "rb") as csvfile:
    reader = csv.reader(csvfile)
    for string in reader:
        string = str(string) 
        string = string.replace("www.", "").replace("http://", "").replace("https://", "")
        new_strings.append(string)

new_strings.sort()
print new_strings #for testing only; will be removed once function is working

cleaned_file = open("Cleaned_URLS.csv", "w")
writer = csv.writer(cleaned_file)
writer.writerows(new_strings)
cleaned_file.close()

Screenshot of destination file

现在是工作代码:

import csv

new_strings = []    

#replace unwanted elements and add cleaned strings to new list
with open("Backlink_Test.csv", "rb") as csvfile:
    reader = csv.reader(csvfile)
    for string in reader:
        string = str(string) 
        string = string.replace("www.", "").replace("http://", "").replace("https://", "")
        new_strings.append(string)

new_strings.sort()
print new_strings

cleaned_file = open("Cleaned_URLS.csv", "w")
writer = csv.writer(cleaned_file)
for url in new_strings:
    writer.writerow([url])

cleaned_file.close()

2 个答案:

答案 0 :(得分:1)

csvwriter.writerows期望rows的可迭代。 rowcells的可迭代。

你正在用一串字符串喂它。由于字符串是一个字母列表,因此在您的示例中,每个字母都被视为cell - 这正是写入的内容。

你做错了是假设csv.reader输出字符串。它输出rows

<强>更新

for url in urls:
    writer.writerow([url])

答案 1 :(得分:1)

这就是Python在循环字符串而不是列表时所做的事情。检查csv.reader()的返回值并相应地调整您的代码。特别是,string = str(string)会使您的输入变得扁平化。