从Fi打印时缩进项目

2024-04-19 01:22:47 发布

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

我仍在学习Python,所以这似乎是一个基本的问题。我正在学习Python速成课程中的示例问题。我正在尝试读取多个文件并打印/显示每个文件的内容。我想有文本“该文件包含以下宠物的名字:”打印,然后有一个缩进名单的名字如下。你知道吗

我遇到了一个问题,要么是每个文件中的第一个项目/行缩进,要么是一行中的每个字母在自己的行上打印。你知道吗

这是我写的代码。你知道吗

def list_pets(filename):
    """Lists pet names within the file."""
    try:
        with open(filename) as file_object:
            pet_names = file_object.read()
    except FileNotFoundError:
        msg = "Unable to locate file " + filename + "."
        print(msg)
    else:
        print("\nThe file " + filename + " contains the following pets: ")
        pets = ""
        for pet in pet_names:
            pets += pet
        print(pets)

filenames = ['dogs.txt', 'cats.txt', 'birds.txt']
for file in filenames:
    list_pets(file)

下面是上述代码的输出(鸟.txt故意不在文件夹中):

The file dogs.txt contains the following pets:
Buttons
Biscuit
Abby
Sam
Jerry
Obi
Roger


The file cats.txt contains the following pets:
Missy
Brown Cat
Oliver
Seal
Mr Bojangles

Unable to locate file birds.txt.

如何使用\t缩进名称?我试过把print(pets)改成print("\t" + pets),但那似乎只缩进了名字。你知道吗

提前谢谢!我学Python很开心,但这个小家伙把我难住了。你知道吗


Tags: 文件the代码txtobjectnamesfilename名字
3条回答

尝试此操作,然后查看选项卡是否正确报告:

_list = ["Buttons","Biscuit","Abby","Sam","Jerry","Obi","Roger"]

indent = "\t"
for l in _list:
    print("{}{}".format(indent, l))
 ...
 pet_names = file_object.readlines()  # to split the lines
 ...


 for pet in pet_names:
     pets = pets + "\t" + pet +"\n"
 print(pets)

只需在每个名字前面加上\t,在后面加一行

如果你在阅读之后打印宠物的名字,你会看到它们仍然以新的行打印。这是因为read()不会删除换行符。 另外,使用format()格式化字符串。祝你好运!你知道吗

def list_pets(filename):
"""Lists pet names within the file."""
try:
    with open(filename) as file_object:
        pet_names = file_object.read().split('\n')
except FileNotFoundError:
    print("Unable to locate file {}.".format(filename))
else:
    print("The file {} contains the following pets: {}".format(filename, ' ,'.join(pet_names)))

相关问题 更多 >