让Python识别csv文件中的换行字符



新手在这里做第一个项目。

我有一个简单的命令行抽认卡程序。问题和答案存储在以^分隔的csv文件中。我希望该程序能够在csv文件中识别换行符(n)字符,并能够将问题划分为单独的行。我该怎么做呢?

csv文件的示例如下:

question1^answer1
longnquestionnnumber2^answer2

例如,也许我有一个关于linux的问题。然后程序像这样输出问题:

根据下面的图表,用户bob对文件abc.txt有什么访问权限?drwxr-xr-x。17 root root 4096 23:38/drwxr-xr——。10 root root 128 03:38/data -rwxr-xr——。1 Bob Bob 100 21:08/data/abc.txt


当我想让程序显示这样的问题时:

Based on the following diagram, what access would the user bob have on the file abc.txt?
drwxr-xr-x. 17 root root 4096 23:38 /
drwxr-xr--. 10 root root 128  03:38 /data
-rwxr-xr--.  1 bob  bob  100  21:08 /data/abc.txt

那么在csv文件中,问题是这样的

Based on the following diagram, what access would the user bob have on the file abc.txt?ndrwxr-xr-x. 17 root root 4096 23:38 /ndrwxr-xr--. 10 root root 128  03:38 /datan-rwxr-xr--.  1 bob  bob  100  21:08 /data/abc.txt^None

我在网上查了一下,看到有人添加了:newline='n'


我用单引号,双引号,空格尝试了很多不同的变体。我不知道怎么让它工作。

with open(studySet, newline="n") as f:

with open(studySet, newline="n") as f:


我也试着把它放在这里,但没有工作:

fileContents = csv。reader(f, delimiter='^', newLine='n')


这是打开csv文件的代码片段:

with open(studySet) as f:     
fileContents = csv.reader(f, delimiter='^')
flashcards = [{"question":rows[0], "answer":rows[1]} for rows in fileContents] 

如果您可以使用/install pandas,这是一个解决方案:

import pandas as pd
df = pd.read_csv("studySet.csv", sep="^", header=None, names=["question", "answer"]).replace(r'\n','n', regex=True)
txt = "n".join([df.iloc[i]["question"]+"n" + df.iloc[i]["answer"]  for i in df.index])
print(txt)

最新更新