繁体   English   中英

Python 3.3-格式问题

[英]Python 3.3 - Formatting Issue

我创建了2个程序。 第一个编写一个名为celeb.txt的文本文件,其中包含用户输入的名人名称列表。 我的第二个代码读取该列表并显示它。

该代码对这两个程序均有效,但我似乎无法正确设置格式。 我是垂直而不是直线列出的名字。 我也不想将代码合并为1个程序。

好的,这是使用户结束名人名字的第一个代码:

import sys

def main():
myfile = open('celeb.txt', 'w')
celeb = input('Enter celebrity name or Enter to quit ')
if celeb:
    myfile.write(str(celeb)+ '\n')

else:
    sys.exit(0)

myfile.close()
print('File was created and closed')

main()

这是我的代码,该代码读取该.txt并输出名称。 我不知道如何将名称1排列在另一个上方而不是在1条直线上。

def main():
myfile = open('celeb.txt', 'r')

line1 = myfile.readline()

myfile.close()

print(line1)

main()

如果要使用多个名称,请一次使用一个名称:

def get_names(fle):
    with open(fle,"a") as f:   
        while True:
            inp = input("Enter a name or 'q' to quit :")
            if inp == "q":
                return 
            f.write("{}\n".format(inp))

def read_names(fle):
    # open names file 
    with open(fle) as f:
        # iterate over the file 
        # printing a name/line at a time
        for name in f:
            print(name)

或者,如果您在一行中使用多个名称,请让用户将名称分开并在写入之前进行拆分:

def get_names(fle):
    with open(fle,"a") as f:
        inp = input("Enter names separated by a space :")
        f.writelines(("{}\n".format(n) for n in inp.split()))

def read_names(fle):
    with open(fle) as f:
        for name in f:
            print(name)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM