python csv writer编写源代码片段到sing

2024-05-23 16:11:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试将脚本和其他相关信息的源代码片段写入csv文件,其中每个单元格将包含一条信息

期望输出如下:

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是具有函数名(funcName)、代码行数(numLines)和实际源代码(sourceCode)等属性的对象

我现在得到的输出如下所示:

helloWorld, 3, {
printf("hellp, world\n");
}
fooBar, ....

Tags: ofcsv代码name信息numbersource源代码
1条回答
网友
1楼 · 发布于 2024-05-23 16:11:22

根据this site

  1. newlines are represented with a carriage return/newline,
  2. the string should be wrapped in quotes.

然后显示示例:

#!/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

但是,将代码中的所有\n替换为\r\n也会更改代码本身中的那些。所以也许你得找到更好的方法来改变

相关问题 更多 >