Python:创建一个从注释中删除的文件副本

标签 python file-io

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

# this should be able to (create a file if not present yet and) take a file and then write another one with the same contents stripped off comments
# I wasnt able to bring it into a proper work - resulting file empty

f = open("test.dat","w")
# write several lines (the new-line n-symbol)
f.write("line one\nline two\nline three\n# blah blah \n# blah")
#
f.close()
# readline method reads all the characters up to and including the next newline character:
f = open("test.dat","r")
print ( f.read() )
print()
# readlines returns lines including newline character


newf = open("test2.dat","w")
newf.close()
newf = open("test2.dat","r")

while True:
  text = f.readline()
  if text == "":
    break
  if text == "#":
    continue
  newf.write(text)
f.close()
newf.close()

print()

newf = open("test2.dat","r")
print (newf.read())
newf.close()

但是生成的文件是空的并且有 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())

关于Python:创建一个从注释中删除的文件副本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42134736/

相关文章:

python - 选择要写入的 .txt 文件中的行数

python - 使用 DB 数据模型生成 SQLAlchemy 模型、模式和 JSON 响应

python - 如何使用 python 正确检查此正则表达式

Python 请求就像它有一个缓存

python - django对图片上传的可疑操作

python - 我想在 django 社交应用登录后添加自定义字段

制作目录时出现 Python "FileExists"错误

java - 将文件写入 sdcard

perl - 在perl中使用多线程处理文件

java - 从 Jar 文件中的资源复制/提取目录