python csv编写器将源代码片段写入单个单元格
我试图将脚本和其他相关信息的源代码片段写入csv文件,其中每个单元格将包含一条信息 期望的输出如下所示:python csv编写器将源代码片段写入单个单元格,python,csv,Python,Csv,我试图将脚本和其他相关信息的源代码片段写入csv文件,其中每个单元格将包含一条信息 期望的输出如下所示: function name, number of lines, source code helloWorld, 3, { printf("hello, world\n"); } fooBar, 5, { const char *foo = "Hello"; const char *bar
function name, number of lines, source code
helloWorld, 3, {
printf("hello, world\n");
}
fooBar, 5, {
const char *foo = "Hello";
const char *bar = "World!";
fprintf(stdout, "%s %s\n", foo, bar);
return 0;
}
其中,每个源代码片段应位于单个单元格中,同时保留代码结构
代码如下:
with open('functionInformation.csv', 'wb') as csvOut:
csvwriter = csv.writer(csvOut, delimiter = ',')
csvwriter.writerow(['function name', 'number of lines', 'source code'])
for functionObject in functionObjectRepository:
csvwriter.writerow([functionObject.funcName, functionObject.numLines, functionObject.sourceCode])
其中,functionObject是具有函数名称、代码行数和实际源代码等属性的对象
我现在得到的输出如下所示:
helloWorld, 3, {
printf("hellp, world\n");
}
fooBar, ....
根据:
换行符用回车符/换行符表示,
字符串应该用引号括起来。
然后显示示例:
#!/usr/bin/env python2.7
import csv
multiline_string = "this\nis\nsome\ntext" # assign string
multiline_string = multiline_string.replace('\n','\r\n') # convert newlines to newlines+carriage return
with open('xyz.csv', 'wb') as outfile:
w = csv.writer(outfile) # assign csv writer method
w.writerow(['sometext',multiline_string]) # append/write row to file
但是,将代码中的所有\r\n替换为\r\n也会更改代码本身中的。因此,您可能需要找到更好的方法来进行更改。您是否注意到了fprintfstdout,%s%s\n,foo,bar;,要查看内部\n是否也正在被替换?由于每行代码都用分号分隔,因此您可能应该替换\n与\r\n。