【问题标题】:How to format a text file such that it removes blank files and trailing space如何格式化文本文件以删除空白文件和尾随空格
【发布时间】:2020-07-02 15:59:37
【问题描述】:

我有像截图一样的test.txt

PS:第二行有尾随空格,所以是 line 2

结果我们必须得到:

第 1 行
第 2 行
第 3 行

这是我目前所拥有的

with open("test", 'r+') as fd:
    lines = fd.readlines()
    fd.seek(0)
    fd.writelines(line for line in lines if line.strip())
    fd.truncate() 

但它不处理行以空格开头的情况(在示例中为第 2 行),我该如何修改我的代码?我要我们Python

【问题讨论】:

    标签: python text nlp


    【解决方案1】:

    Test.txt 文件:

    first line
    
         second line
    third line
    

    Python 代码:

    #// Imports
    import os
    #// Global Var's
    fileName:str = "test.txt"
    
    #// Logic
    def FileCorection(file:str):
        try:
            #// Read original file
            with open(file, "r") as r:
                #// Write a temporary file
                with open(f"temp_{file}", "w") as w:
                    # Get line from original file
                    line = r.readline()
    
                    # While we still have lines
                    while line:
                        # Make a temporary line with out spaces at the end and also at the front of the line (in case they are)
                        tempLine:str = line.strip()
                        #// Check if the line is empty
                        if tempLine == "":
                            Line:tuple = (False, "Empty line...")
                        #// If not then get the line
                        else:
                            Line:tuple = (True, tempLine)
    
                        #// Print/Show Line if is True... in this case you care set witch line to pre writed in a new file
                        if Line[0] == True:
                            print(Line[1])
                            w.write(f"{Line[1]}\n")
    
                        line = r.readline()
        finally:
            # Make shore the files are closed
            # By default they shood but just to make shore
            r.close()
            w.close()
    
            # Now repalce the temp file with the original one
            # By replaceing we delete the original one and we rename the temporary one with the same name
            os.remove(file)
            os.rename(f"temp_{file}", file)
    
    if __name__ == "__main__":
        FileCorection(fileName)
        # Show when is done
        print(">> DONE!")
    

    控制台输出:

    first line
    second line
    third line
    >> DONE!
    
    Process finished with exit code 0
    

    P.S.:代码已更新/优化!

    【讨论】:

    • 我还想用新格式更新我的 test.txt。我们将不得不将输出写入文本文件。你也可以帮忙吗
    • @AayushGupta 完成 :)
    • @AayushGupta 我通过删除 useles 代码更新了代码,并添加了更多 cmets 来解释这行代码的含义:)
    【解决方案2】:

    我建议格式化输入(文本文件的屏幕截图可以)。假设您的输入看起来像这样,您可以在文本以空格开头时使用 strip。

    #Code
    with open(r"demo.txt","r") as f:
        data = f.read()
    
    data_list = [s.strip() for s in data.split("\n") if len(s)>0]
    print("\n".join(data_list))
    

    【讨论】:

    • 我已按要求添加截图
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-30
    • 1970-01-01
    • 1970-01-01
    • 2017-05-31
    • 2010-09-14
    • 2012-09-24
    相关资源
    最近更新 更多