Python 使字符串对CSV写入安全吗?
我需要使用打印语句写入CSV文件,因此无法使用CSV writer库。但是,正如预期的那样,逗号将字符串分成不同的列。如何在写入之前通过转换字符串来转义逗号 例如:Python 使字符串对CSV写入安全吗?,python,csv,export-to-csv,Python,Csv,Export To Csv,我需要使用打印语句写入CSV文件,因此无法使用CSV writer库。但是,正如预期的那样,逗号将字符串分成不同的列。如何在写入之前通过转换字符串来转义逗号 例如: my_str = 'I have apples, pears, and bannanas' with open('test.csv','w', newline='') as out: print(my_str, file = out) 我需要这样一个函数: def csv_formatter(string): #
my_str = 'I have apples, pears, and bannanas'
with open('test.csv','w', newline='') as out:
print(my_str, file = out)
我需要这样一个函数:
def csv_formatter(string):
# transform string here
return csv_safe_string
我尝试按照其他帖子的建议将字符串括在引号中,但没有成功。不要尝试模拟
csv
模块,只需将其与io.StringIO结合使用,以模拟文件输出:
import csv,io
def csv_formatter(string):
outstream = io.StringIO() # "fake" output file
cw = csv.writer(outstream) # pass the fake file to csv module
cw.writerow([string]) # write a row
return outstream.getvalue() # get the contents of the fake file
print(csv_formatter("I have apples, pears, and bananas"))
结果:
"I have apples, pears, and bananas"
另外,一个很好的副作用是将引号考虑在内:更改为:
print(csv_formatter('I have apples, "pears", and bananas'))
您将得到(注意引号中的双引号):
请注意,这是在编写一个只有一列的文件。但同样的情况也适用于超过一列的情况。例如,将写入行替换为:
cw.writerow([string,string,12])
您将获得:
"I have apples, pears, and bananas","I have apples, pears, and bananas",12
现在我想知道为什么不能将print
与csv
输出混合,只需共享文件句柄即可:
with open('test.csv','w', newline='') as out:
print("Raw Hello", file = out)
csv.writer(out).writerow('I have apples, pears, and bananas')
print("Raw Goodbye", file = out)
不要试图模拟csv
模块,只需使用它,结合io.StringIO
来模拟文件输出:
import csv,io
def csv_formatter(string):
outstream = io.StringIO() # "fake" output file
cw = csv.writer(outstream) # pass the fake file to csv module
cw.writerow([string]) # write a row
return outstream.getvalue() # get the contents of the fake file
print(csv_formatter("I have apples, pears, and bananas"))
结果:
"I have apples, pears, and bananas"
另外,一个很好的副作用是将引号考虑在内:更改为:
print(csv_formatter('I have apples, "pears", and bananas'))
您将得到(注意引号中的双引号):
请注意,这是在编写一个只有一列的文件。但同样的情况也适用于超过一列的情况。例如,将写入行替换为:
cw.writerow([string,string,12])
您将获得:
"I have apples, pears, and bananas","I have apples, pears, and bananas",12
现在我想知道为什么不能将print
与csv
输出混合,只需共享文件句柄即可:
with open('test.csv','w', newline='') as out:
print("Raw Hello", file = out)
csv.writer(out).writerow('I have apples, pears, and bananas')
print("Raw Goodbye", file = out)
只需按以下方式设置字符串:
my_str = '"I have apples, pears, and bannanas"'
只需按以下方式设置字符串:
my_str = '"I have apples, pears, and bannanas"'
那么您想创建一个类似于csv的1列输出吗?是的,正确!我想将字符串打印到一个单元格中。您需要一个接受“安全”字符串的csv文件读取器。引用整体为“我有苹果、梨和香蕉”,22、44“
应该这样做才能得到3个列您想创建一个类似csv的1列输出吗?是的,正确!我想将字符串打印到一个单元格中。您需要一个接受“安全”字符串的csv文件读取器。引用“我有苹果、梨和香蕉”这句话,22、44“应该可以得到3个小柱