2016-11-08 51 views
0
fp = open ('data.txt','r') 
saveto = open('backup.txt','w') 
someline = fp.readline() 
savemodfile = '' 
while someline : 
    temp_array = someline.split() 
    print('temp_array[1] {0:20} temp_array[0] {0:20}'.format(temp_array[1], temp_array[0]), '\trating:', temp_array[len(temp_array)-1])) 
    someline = fp.readline() 
    savemodfile = temp_array[1] + ' ' + temp_array[0] +',\t\trating:'+ temp_array[10] 
    saveto.write(savemodfile + '\n') 
fp.close() 
saveto.close() 

输入文件:data.txt中有这种模式的记录:名姓年龄地址格式化输出到外部txt文件

我想为Backup.txt到具有以下格式:姓氏名字地址年龄

如何将数据以不错的格式存储在backup.txt中?我认为我应该使用format()方法......

我使用代码中的打印对象向你展示了我对format()的理解。当然,我没有得到理想的结果。

+1

刚才你的意思是“一种不错的格式化方式”?您可以让每个字段都具有预定数量的字符,但缺点是较长的值可能不适合。您可以用逗号,空格或引号分隔字段,但会阻止这些字符位于字段中。除非您提供关于数据和您想要的更多细节,否则我们无法为您提供帮助。 –

回答

0

要回答你的问题: 你的确可以使用.format()方法上的绳子模板,请参阅文档https://docs.python.org/3.5/library/stdtypes.html#str.format

例如:

'the first parameter is {}, the second parameter is {}, the third one is {}'.format("this one", "that one", "there") 

将输出:'the first parameter is this one, the second parameter is that one, the third one is there'

你做在您的情况下似乎没有正确使用format()'temp_array[1] {0:20} temp_array[0] {0:20}'.format(temp_array[1], temp_array[0])会输出类似'temp_array[1] Lastname temp_array[0] Lastname '的东西。这是因为{0:20}会将第一个参数输出到format(),右侧用20个字符的空格填充。

此外,代码中还有许多需要改进的地方。我想你正在学Python,所以这很正常。这里是产生你想要的输出功能相当的代码,并充分利用Python的功能和语法:

with open('data.txt', 'rt') as finput, \ 
    open('backup.txt','wt') as foutput: 
    for line in finput: 
     firstname, lastname, age, address = line.strip().split() 
     foutput.write("{} {} {} {}\n".format(lastname, firstname, address, age) 
+0

拆分和剥离两者都删除空白(因为它们没有参数)。你可以解释为什么你不仅仅使用拆分或只剥离?我不明白strip.split想要“捕捉”什么。 – Mynicks

+0

'strip()'将在行的开始和/或结束处删除不必要的空白。如果没有这样的空格,那么它返回相同的字符串。它不会更改任何空格_字符串。 'split()'会将字符串剪切为空格作为分隔符并返回结果字符串列表。 'strip()'在你的情况下可能不是必须的,但它不会伤害:) – Guillaume

+0

另外,如何正确关闭这两个文件? finput.close()和foutput.close()throw SyntaxError – Mynicks

0

此代码会给你在屏幕上,并在输出文件格式输出

fp = open ('data.txt','r') 
saveto = open('backup.txt','w') 
someline = fp.readline() 
savemodfile = '' 
while someline : 
    temp_array = someline.split() 
    str = '{:20}{:20}{:20}{:20}'.format(temp_array[1], temp_array[0], temp_array[2], temp_array[3]) 
    print(str)  
    savemodfile = str 
    saveto.write(savemodfile + '\n') 
    someline = fp.readline()  

fp.close() 
saveto.close() 

但是,这不是一个很漂亮的代码在处理文件,请尝试使用以下模式:

with open('a', 'w') as a, open('b', 'w') as b: 
    do_something() 

参考:How can I open multiple files using "with open" in Python?

0
fp = open ('data.txt','r') 
saveto = open('backup.txt','w') 
someline = fp.readline() 
savemodfile = '' 
while someline : 
    temp_array = someline.split() 
    someline = fp.readline() 
    savemodfile = '{:^20} {:^20} {:^20} {:^20}'.format(temp_array[1],temp_array[0],temp_array[3],temp_array[2]) 
    saveto.write(savemodfile + '\n') 
fp.close() 
saveto.close()