对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'
)您的案例的惯用代码可以是
相关问题 更多 >
编程相关推荐