Python3 - 对于 ROW 而不是 lin 中的 fd

2024-09-24 02:24:25 发布

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

有没有可能在一行中用“,”分开,然后作为一行单独打印出来

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

Tags: nameappledatalineopenpeoplesubjectprint
2条回答
line = line.lstrip().rstrip().split(", ")[i]

这一行用逗号分隔这一行,并取第i个元素(它适用于i=0、1,可能还有2,但一旦i变大,就会出现异常)

你真正想做的是-

subject, name, fruit = line.lstrip().rstrip().split(", ")

然后打印每个变量,但更优雅的方法是使用csv reader

代码当前不起作用的原因是,在您给出的示例中,每行(line = ...[i])取一个固定项,其中i在打印不同的行时不变

假设您的文件始终包含相同的结构Subject, Name, Fruit,我将使用zip()来循环行:

fd = open("data.txt", "r").readlines()
labels = ['Subject', 'Name', 'Fruit']

for line_num, line in enumerate(fd):
    line = line.lstrip().rstrip()
    for label, item in zip(labels, line.split(', '):
        print("%s-%d: %s" % (label, line_num, item))

此外,我将用“更现代”的版本替换您的打印声明:

print(f'{label}-{line_num}: {item}')

或者如果您在一个版本中工作<;第3.6条

print('{}-{}: {}'.format(label, line_num, item)

但这主要是个人喜好

相关问题 更多 >