Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/347.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
用Python编写CSV文件_Python_Pandas_Csv - Fatal编程技术网

用Python编写CSV文件

用Python编写CSV文件,python,pandas,csv,Python,Pandas,Csv,我编写了一个python脚本来访问一个站点,并在该站点上为我做了一次特定的搜索,以扫描搜索结果 我将结果的返回写为txt clear = self.browser.find_elements_by_class_name('Whitebackground') for scrape in clear: with open('result.txt', 'a') as writer: writer.write(scrape.text) writer.write

我编写了一个python脚本来访问一个站点,并在该站点上为我做了一次特定的搜索,以扫描搜索结果

我将结果的返回写为
txt

clear = self.browser.find_elements_by_class_name('Whitebackground')
for scrape in clear:
    with open('result.txt', 'a') as writer:
         writer.write(scrape.text)
         writer.write('\n')
         writer.close()
我想返回CSV格式的结果,以便在Excel中打开

clear = self.browser.find_elements_by_class_name('Whitebackground')
    for scrape in clear:
        with open('result.csv', 'a') as writer:
             writer.write(scrape.text)
             writer.write('\n')
             writer.close()
我的问题是我必须填写4列

我就是这样得到我现在的结果的

656473930362736
The car needs to change the oil
Model: sedan
type of fuel: Gasoline
我希望以这种方式接收CSV中的结果

'Number'; 'description'; 'Model'; 'Type of fuel'
6564...; The car needs..; sedan ; Gasoline
“编号”
“说明”
“型号”
,“
燃料类型”
将按列列出标题

“6564…”
“汽车需要…”
“轿车”
“汽油”
将是列中的行


有人知道我该怎么做吗???

如果你能将数据转换成字典,那就太简单了:

data = []
datapoint = {}
datapoint['Number'] = 656473930362736
datapoint['Description'] = "The car needs to change the oil."
datapoint['Model'] = "Sedan"
datapoint['Type of Fuel'] = "Gasoline"
data.append(datapoint)

fieldnames = ['Number','Description','Model','Type of Fuel']

def filewriter(filename, data, fieldnames):
        with open (filename, "w", newline='', encoding='utf-8-sig') as csvfile:
                csvfile = csv.DictWriter(csvfile, fieldnames=fieldnames, delimiter=',', dialect='excel')
                csvfile.writeheader()
                for row in data:
                        csvfile.writerow(row)

filewriter("out.csv", data, fieldnames)

将数据转换为字典是一个单独的问题,但如果数据结构良好,则应该没有什么大不了的。

只需通过拆分为元素来解析文本:

txt = "656473930362736\n" \
       "The car needs to change the oil\n" \
       "Model: sedan\n" \
       "type of fuel: Gasoline"

list_of_elements = txt.split('\n')
required_text = list_of_elements[0] + ';' + list_of_elements[1] + ';' list_of_elements[2].split(':')[1] + ';' + list_of_elements[3].split(':') + ';'
file.write(required_text + '\n')

我得到随机值​​写所以我不能做的例子:['Number']=656473930362736其他的也一样。所以这里['Number']=scrap接收值​​他在网站上找到了我说过的——如何将数据转换成字典格式是一个不同的问题,这可能可以用简单的正则表达式解决——但如果没有看到一些例子,我就不能肯定。