【问题标题】:Reading strings from csv does not print \n [closed]从 csv 读取字符串不打印 \n [关闭]
【发布时间】:2020-02-18 21:24:13
【问题描述】:

我正在从 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)

【问题讨论】:

标签: python python-3.x csv newline


【解决方案1】:

目前尚不清楚您希望如何解释 csv 文件中的数据,但这是一个猜测。它使用ast.literal_eval()函数将输入数据中的转义字符转换为换行符。

这涉及将第二列括在 triple 双引号 (""") 字符中,以便将其解释为 Python 字符串文字。如果封闭的文本本身包含引号,则使用三引号。例如:Dest, Test\n "Test2"\n Test3

import ast
import csv

filename = '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

【讨论】:

  • 谢谢你,这正是我所需要的!
【解决方案2】:

如果我理解正确,您想用换行符替换输入中的文字字符 '\' 和 'n' 的序列:

代替:

message = str(message)

你想要:

message = message.replace('\\n', '\n')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-02-15
    • 1970-01-01
    • 1970-01-01
    • 2015-01-23
    • 1970-01-01
    • 2014-12-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多