Python:创建从注释中剥离的文件副本

Python:创建从注释中剥离的文件副本,python,file-io,Python,File Io,对于Python来说还是新手,尝试学习一本书中的示例。这将创建一个文本文件副本,从以#注释开头的所有行中删除。它是这样的(包括我的实习生评论): 但生成的文件为空且具有0b。我能谦虚地问一下怎么了?谢谢 您的代码有几个问题: 您打开输入文件进行读取,并在print(f.read())中使用了所有输入文件;文件指针现在位于文件的末尾 输出文件被打开进行写入,但随后立即关闭,从而创建了一个空文件。然后打开此空文件进行读取 循环一开始就退出,因为文件末尾的readline()将返回一个空字符串' 您

对于Python来说还是新手,尝试学习一本书中的示例。这将创建一个文本文件副本,从以#注释开头的所有行中删除。它是这样的(包括我的实习生评论):


但生成的文件为空且具有0b。我能谦虚地问一下怎么了?谢谢

您的代码有几个问题:

  • 您打开输入文件进行读取,并在
    print(f.read())
    中使用了所有输入文件;文件指针现在位于文件的末尾

  • 输出文件被打开进行写入,但随后立即关闭,从而创建了一个空文件。然后打开此空文件进行读取

  • 循环一开始就退出,因为文件末尾的
    readline()
    将返回一个空字符串
    '

  • 您的
    if
    不会检查每行的第一个字符,而是将整行与
    #
    匹配。由于该行还包含换行符,因此即使是一行中的
    也不会匹配此条件(
    readline
    将返回
    '\n'


您案例的惯用代码可能是

with open('test.dat', 'w') as output_file:
    # write several lines (the new-line n-symbol)
    output_file.write("line one\nline two\nline three\n# blah blah \n# blah")
# file closed automatically

with open('test.dat') as input_file:
    print(input_file.read())
    print()
# closed automatically

# reopen input file, open output file
with open('test.dat') as input_file, open('test2.dat', 'w') as output_file:
    for line in input_file:
        if not line.startswith('#'):
            output_file.write(line) 
# both files again closed automatically at the end of with block

print('Contents of test2.dat are now:')
with open('test2.dat') as input_file:
    print(input_file.read())

清空test2.dat后,您将打开它进行阅读。然而你却试着写进去。但是,您也已经完整地阅读了
test.dat
,文件指针现在设置为文件的结尾,因此没有任何内容可以读取,
f.readline()
将立即返回空字符串,从而中断您的循环。也许可以使用更多的调试打印来查看正在执行的代码及其原因。这是哪本书?在过去的15年里,这不是惯用的python吗?我不建议你阅读这样一本书?我添加了一种更为惯用的方法,可惜没有“完美的Python自学书”。对于一个只编写了10天代码的人来说,你做得很好。谢谢。这个“with-as”的概念对我来说是全新的,但看起来非常优雅。
with open('test.dat', 'w') as output_file:
    # write several lines (the new-line n-symbol)
    output_file.write("line one\nline two\nline three\n# blah blah \n# blah")
# file closed automatically

with open('test.dat') as input_file:
    print(input_file.read())
    print()
# closed automatically

# reopen input file, open output file
with open('test.dat') as input_file, open('test2.dat', 'w') as output_file:
    for line in input_file:
        if not line.startswith('#'):
            output_file.write(line) 
# both files again closed automatically at the end of with block

print('Contents of test2.dat are now:')
with open('test2.dat') as input_file:
    print(input_file.read())