有没有可能在一行中用“,”分开,然后作为一行单独打印出来
fd = open("data.txt", "r").readlines()
i = 0
for line in fd:
line = line.lstrip().rstrip().split(", ")[i]
print("Subject-%d: %s" % (i, line))
print("Name-%d: %s" % (i, line))
print("Fruit-%d: %s" % (i, line))
i += 1
文本文件包含以下内容:
People, Zeref, Apple
Greeks, Zues, Apricot
基本上我想让代码做的是将文本文件按“,”分开,然后将每个文件打印到新行上,这样就可以
Subject-0: People
Name-0: Zeref
Fruit-0: Apple
Subject-1: Greeks
Name-1: Zues
Fruit-1: Apricot
因为某种原因它只是说
Subject-0: People
Name-0: People
Fruit-0: People
Subject-1: Greeks
Name-1: Greeks
Fruit-1: Greeks
这一行用逗号分隔这一行,并取第i个元素(它适用于i=0、1,可能还有2,但一旦i变大,就会出现异常)
你真正想做的是-
然后打印每个变量,但更优雅的方法是使用csv reader
代码当前不起作用的原因是,在您给出的示例中,每行(
line = ...[i]
)取一个固定项,其中i
在打印不同的行时不变假设您的文件始终包含相同的结构
Subject, Name, Fruit
,我将使用zip()
来循环行:此外,我将用“更现代”的版本替换您的打印声明:
或者如果您在一个版本中工作<;第3.6条
但这主要是个人喜好
相关问题 更多 >
编程相关推荐