【问题标题】:Copying contents of a file into another in File Handling在文件处理中将文件的内容复制到另一个文件中
【发布时间】:2021-11-02 17:48:49
【问题描述】:

我想将忽略代码中的 cmets 的 Python 脚本复制到另一个文件。我已经尝试了下面的代码,但它复制了包括 cmets 在内的所有代码行。请让我知道如何纠正它。我是 Python 编程的新手。

with open("essays.txt",'rb') as f1:
    with open("myfile.txt",'wb') as f2:
        while True:
            buf=f1.readline()
            if len(buf)!=0:
                if buf[0]=='#':
                    continue
                else:
                    f2.write(buf)
                    
            else:
                break
print("File Copied")

以上是将file1的所有内容复制到file2中,包括输出中不需要的cmets。

【问题讨论】:

    标签: while-loop file-handling readline with-statement continue


    【解决方案1】:

    我已检查您的代码在第一个字符是 # 时是否正常工作。现在想象一下,如果开头有空格或制表符,那么您的代码将无法正常工作。

    请试试下面的代码,去掉字符串左边的空格和制表符,然后检查第一个字符。

        with open("createEntitiesFromDB.py",'rb') as f1:
                with open("myfile.txt",'wb') as f2:
                        while True:
                                buf=f1.readline()
    
                                if len(buf)!=0:
                                        buf2 = buf.lstrip()
                                        if len(buf2)!=0:
                                                if buf2[0]=='#':
                                                        continue
                                                else:
                                                        f2.write(buf)
                                        else:
                                                f2.write(buf)
                                        
                                else:
                                        break
        print("File Copied")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-11-24
      • 1970-01-01
      • 2013-04-26
      • 2011-06-03
      • 1970-01-01
      • 1970-01-01
      • 2010-11-02
      • 1970-01-01
      相关资源
      最近更新 更多