[英]How do create a python program that would save strings in csv but all in one block of that row?
I want this to be done我希望做到这一点
This is what I want.这就是我要的。 I have a script that gets the strings portion but whenever I try to append or write it into a CSV file it is not getting on the same block rather the strings are put in different block in a row.
我有一个获取字符串部分的脚本,但是每当我尝试将其附加或写入 CSV 文件时,它都不会出现在同一个块中,而是将字符串连续放入不同的块中。 Current script does this , and I don't want this.
当前脚本执行此操作,我不想要此操作。
final_string = "usafndoas asidnkas ,dioas ais asonxxk asd ascioasopasn xasix xaso asoid"
file = open("protagonist.csv", 'w+')
writer = csv.writer(file)
file.write(str(final_string))
How do I do it?我该怎么做? It is putting it into separate blocks in a row.
它将它连续放入单独的块中。 But I want it on same block if possible..
但如果可能的话,我希望它在同一个街区。
You need to use the csvwriter.writerow()
function.您需要使用
csvwriter.writerow()
函数。 This takes a list of items and places each entry into its own cell in the CSV file.这需要一个项目列表,并将每个条目放入 CSV 文件中的自己的单元格中。
So to write final_string
as a single value (eg A1 in Excel) you can do the following:因此,
final_string
写为单个值(例如 Excel 中的 A1),您可以执行以下操作:
import csv
final_string = "usafndoas asidnkas ,dioas ais asonxxk asd ascioasopasn xasix xaso asoid"
with open("protagonist.csv", 'w+', newline='') as f_output:
csv_output = csv.writer(f_output)
csv_output.writerow([final_string])
The []
has turned final_string
into a list with a single item. []
将final_string
变成了一个包含单个项目的列表。
If you wanted to write other cells (your example shows a C
in A1
) you could change this to:如果您想编写其他单元格(您的示例显示
A1
中的C
),您可以将其更改为:
csv_output.writerow(["C", final_string])
This would create two cells.这将创建两个单元格。
Note: Using with
here has the effect of automatically closing the file for you at the end.注意:
with
此处使用with
具有最后自动为您关闭文件的效果。
import pandas as pd
df = pd.read_csv(r"C:\\Users\\DELL\\Desktop\\Final project\\Requirements2.csv",encoding = 'unicode_escape')
print(df)
试用此代码并为此代码提供您自己的 .csv 文件路径。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.