Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/328.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 格式化文本文件中的字符串_Python_Python 3.x_Text Files_String Formatting - Fatal编程技术网

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

Python 格式化文本文件中的字符串,python,python-3.x,text-files,string-formatting,Python,Python 3.x,Text Files,String Formatting,我正在尝试格式化从.txt文件中读取的逐行文本。首先,我只是想弄清楚如何只打印一行,然后再打印多行。我已经设法打印了一行的文本,但是当我尝试按我希望的方式格式化它时,在我尝试打印该行的最后一个字(使用索引-1)后,会创建一个新行。最后一个字是创建一个新行,所以我想我需要找到一种方法将这些行作为单独的字符串来读取,但我不确定 这是我的程序的代码: def makeTuple (employee): myTuple = employee.split(" ") payroll, sa

我正在尝试格式化从.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

您可以使用拆分和联接来完成此操作:

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

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

您可以使用拆分和联接来完成此操作:

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

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

您将在“辛普森”之后获得一个换行符,因为这是文本文件中的内容

读取换行符时,使用函数
strip()
()删除换行符

更改以下一行代码,您的程序就可以运行了

record = text_file.readline().strip()

您将在“辛普森”之后获得一个换行符,因为这是文本文件中的内容

读取换行符时,使用函数
strip()
()删除换行符

更改以下一行代码,您的程序就可以运行了

record = text_file.readline().strip()
读取文件时使用
strip()
删除换行符:
record=text\u file.readline().strip()
读取文件时使用
strip()
删除换行符:
record=text\u file.readline().strip()