一周前开始使用Python,我有一些关于阅读和写入相同文件的问题.我已经在线阅读了一些教程,但我仍然对此感到困惑.我可以理解简单的读写文件.
openFile = open("filepath", "r")
readFile = openFile.read()
print readFile
openFile = open("filepath", "a")
appendFile = openFile.write("\nTest 123")
openFile.close()
Run Code Online (Sandbox Code Playgroud)
但是,如果我尝试以下操作,我会在写入的文本文件中收到一堆未知文本.任何人都可以解释为什么我会收到这样的错误,为什么我不能使用相同的openFile对象,如下所示.
# I get an error when I use the codes below:
openFile = open("filepath", "r+")
writeFile = openFile.write("Test abc")
readFile = openFile.read()
print readFile
openFile.close()
Run Code Online (Sandbox Code Playgroud)
我会尽力澄清我的问题.在上面的示例中,openFile是用于打开文件的对象.如果我想第一次写它,我没有问题.如果我想使用相同的openFile来读取文件或附加内容.它不会发生或给出错误.在我可以对同一个文件执行另一个读/写操作之前,我必须声明相同/不同的打开文件对象.
#I have no problems if I do this:
openFile = open("filepath", "r+")
writeFile = openFile.write("Test abc")
openFile2 = open("filepath", "r+")
readFile = openFile2.read()
print readFile
openFile.close()
Run Code Online (Sandbox Code Playgroud)
如果有人能告诉我这里做错了什么,或者只是一个Pythong的事情,我将不胜感激.我使用的是Python 2.7.谢谢!
我正在Linux系统上使用一个非常大的(~11GB)文本文件.我正在通过检查文件错误的程序运行它.一旦发现错误,我需要修复该行或完全删除该行.然后重复......
最后,一旦我对这个过程感到满意,我会完全自动完成它.但是现在,让我们假设我正在手动操作.
从这个大文件中删除特定行的最快(在执行时间方面)方法是什么?我想在Python中做到这一点......但是会对其他例子持开放态度.该行可能位于文件中的任何位置.
如果是Python,请假设以下界面:
def removeLine(filename, lineno):
谢谢,
-AJ
我有一个文件"test.txt":
this is 1st line
this is 2nd line
this is 3rd line
Run Code Online (Sandbox Code Playgroud)
以下代码
lines = open("test.txt", 'r')
for line in lines:
print "loop 1:"+line
for line in lines:
print "loop 2:"+line
Run Code Online (Sandbox Code Playgroud)
只打印:
loop 1:this is 1st line
loop 1:this is 2nd line
loop 1:this is 3rd line
Run Code Online (Sandbox Code Playgroud)
它根本不打印loop2.
两个问题:
open()返回的文件对象是可迭代的吗?这就是为什么它可以用于for循环?
为什么loop2根本没有印刷?