繁体   English   中英

在Python中:如何将文本文件中的元素打印为字符串,就像出现在文件中一样?

[英]In Python: How do I print the elements as a string from a text file the same way as it appears in the file?

我的文件名为data.txt,其中包含:

First, Last, GPA, Major, Drops
Jane, Doe, 3.5, CS, 2
Joe, Doe, 2.0  , CpE, 0
Todd,Brown,3.88,CS,5
Mike,Smith,   3.88   , CS  , 5

我必须从文件中打印一张表格,该表格如下所示:

First, Last, GPA, Major, Drops
Jane, Doe, 3.5, CS, 2
Joe, Doe, 2.0, CpE, 0
Todd, Brown, 3.88, CS, 5
Mike, Smith, 3.88, CS, 5

到目前为止,我的代码是:

fp = open('data.txt','r')
str1 = ""
for line in fp:
    a = line.strip().replace("   ", " ").replace("   ,", ",")
    str1 += str(a) + '\n'
fp.close()
print(str1)

我在空间上挣扎着。 文件中的文本间距太大或缺少空格。 示例:对于最后一行,我想像这样打印:

Mike, Smith, 3.88, CS, 5

但是它出现在文件的文本中:

Mike,Smith,   3.88   , CS  , 5

尝试此操作, split行,然后strip空格,然后使用逗号和sapce join list

with open('test1.txt') as fp:
    for line in fp:
        a = [item.strip() for item in line.split(',')]
        print ', '.join(a)

或者您也可以使用map功能

a = map(str.strip, line.split(','))

输出: -

First, Last, GPA, Major, Drops
Jane, Doe, 3.5, CS, 2
Joe, Doe, 2.0, CpE, 0
Todd, Brown, 3.88, CS, 5
Mike, Smith, 3.88, CS, 5

根据空格分割字符串,然后用一个空格重新连接

fp.close()
str1 = ' '.join(str1.split())
print(str1)

暂无
暂无

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

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