格式化文本文件中的字符串

2024-10-01 00:16:52 发布

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

我正在尝试格式化从.txt文件中逐行读取的文本。首先我只是想弄清楚如何只打印一行,然后再打印多行。我已经设法打印了一行的文本,但当我试图格式化它的方式,我希望它看起来,一个新的行创建后,我试图打印该行的最后一个字(使用索引-1)。最后一个词是创建一个新行,所以我想我需要找到一种方法来将这些行作为单独的字符串来读取,但我不确定。你知道吗

这是我的程序代码:

def makeTuple (employee):

    myTuple = employee.split(" ")
    payroll, salary, job_title, *othernames, surname = myTuple
    myTuple = tuple(myTuple)
    return(myTuple)

def printTuple (data):

    employee_str = "{}, {} {:>8} {} {:>5}"
    print(employee_str.format(data[-1], " ".join(data[3:-1], data[0], data[2], data[1]))


get_file = input(str("Please enter a filename: "))    
path = get_file + ".txt"

try:
    text_file = open(path, "r")
except IOError:
    print('The file could not be opened.')
    exit()


record = text_file.readline()

myTuple = makeTuple(record)
printTuple(myTuple)

这是我正在读取的文本文件:

12345 55000 Consultant Bart Simpson
12346 25000 Teacher Ned Flanders
12347 20000 Secretary Lisa Simpson
12348 20000 Wizard Hermione Grainger

我现在得到的结果是:

Simpson
, Bart    12345 Consultant 55000

但我希望它看起来像:

Simpson, Bart    12345 Consultant 55000

Tags: 文本txtdatagetdefemployeefileprint
2条回答

您可以使用“拆分和联接”来执行此操作:

s = '''Simpson
, Bart    12345 Consultant 55000'''

print(''.join(s.split('\n')))

"Simpson"之后会有一个新行,因为这是文本文件中的内容。你知道吗

使用函数strip()Documentation)在读取行时删除换行符。你知道吗

更改下面的一行代码,您的程序就可以运行了。你知道吗

record = text_file.readline().strip()

相关问题 更多 >