猿问

从 csv 读取字符串不会打印 \n

我正在从 csv 文件中读取字符串。这些字符串包含“\n”字符来表示新行。如何使用正确的新行打印这些字符串?使用 str() 不起作用。


CSV 文件只有一行:


Dest, Test\n Test2\n Test3

以下代码打印Test\n Test2\n Test3


for ifile in files:

    with open(orderPath + '\\' + ifile) as csv_file:

        csv_reader = csv.reader(csv_file, delimiter=',')


        for row in csv_reader:


            dest = row[0]

            message = row[1]


            message = str(message)

            print(message)


隔江千里
浏览 111回答 2
2回答

慕村9548890

目前尚不清楚您希望如何解释csv文件中的数据,但这里有一个猜测。它使用 ast.literal_eval() 函数将输入数据中的转义字符转换为换行符。这涉及将第二列括在三重双引号()字符中,以允许将其解释为Python字符串文本。如果封闭的文本本身包含引号,则使用三重引号。例如:"""Dest, Test\n "Test2"\n Test3import astimport csvfilename = 'one_line.csv'with open(filename, newline='') as csv_file:    for row in csv.reader(csv_file, delimiter=','):        dest = row[0]        message = ast.literal_eval('"""{}"""'.format(row[1]))        print(dest)        print(message)输出:Dest Test Test2 Test3

繁花如伊

如果我理解正确,您希望将输入中的文字字符“\”和“n”序列替换为换行符:而不是:message = str(message)你想要:message = message.replace('\\n', '\n')
随时随地看视频慕课网APP

相关分类

Python
我要回答