我正在编写一个程序,我希望它能够创建和读取一个txt文件。我研究了一下,发现了open()
,但是我试着用这样的方法测试它,我发了一个简单地说“你好”而没有引号的txt文件,我称之为程序readnwrite:
open(readnwrite,r)
但我不确定如何挑选某个程序的某些部分,或者喜欢它是否可以将代码写入文件以便以后访问它。我还想制作一些东西,以便它可以测试是否存在某个名称的文件,如果它不是,则创建一个。
答案 0 :(得分:1)
使用内置函数open()
:
readnwrite.txt
:
Hello World!
This is a test
Love from,
me...
然后,您可以执行以下操作:
>>> myfile = open("readnwrite.txt", "r+") #The "r+" specifies we want to read and write
>>> for line in myfile:
... print line
...
Hello World!
This is a test
Love from,
me...
>>>
如果要编写,请使用内置的write()
函数:
>>> myfile.write('Hello, this is not a joke!')
>>> myfile.close()
更新了readnwrite.txt
:
Hello World!
This a test
Love from,
me...
Hello, this is not a joke!
如果在调用write
后调用read()
函数,或只是读取文件,它会在文件末尾打印出您的文本,因为阅读已经将我们带到了最后。但是,如果您先调用write()
,则会将其写入顶部,重叠所有以前的文字:
>>> myfile = open("readnwrite.txt", "r+")
>>> myfile.write("This should be at the top of the file now.")
>>> myfile.close()
更新了readnwrite.txt
:
This should be at the top of the file now..
Hello, this is not a joke!
正如您所看到的,新的write()
重叠了一切。现在让我们看看它是否真的重叠了。
我们将手动更新readnwrite.txt
,并输入重叠的文字:
更新了readnwrite.txt
:
Hello World!
This a test
Love from,
me..
现在,如果这是正确的,则此长度应比字符串1
的长度"This should be at the top of the file now."
多1
。为什么Hello World!
This a test
Love from,
me..
?因为每行末尾都有一个新行:
Hello World!\n
\n
This a test\n
\n
Love from,\n
me..\n
实际上是
'\n'
将>>> myfile = open("readnwrite.txt", "r").read()
>>> myfile
'Hello World!\n\nThis a test\n\nLove from,\nme..\n'
>>> print myfile
Hello World!
This a test
Love from,
me..
>>>
s作为新行的转义序列:
>>> myfile = open("readnwrite.txt", "r").read()
>>> myfile
'Hello World!\n\nThis a test\n\nLove from,\nme..\n'
>>> len(myfile)
43
>>> len("This should be at the top of the file now.")
42
>>> len(myfile) - len("This should be at the top of the file now.")
1
>>>
获取长度:
{{1}}
希望这有帮助!
答案 1 :(得分:0)
# write "hello" to a text file
with open("mytextfile.txt", "w") as outf:
outf.write("hello")
# read it back in
try:
with open("mytextfile.txt", "r") as inf:
data = inf.read()
print(data) # => prints "hello"
except FileNotFoundError as err:
print(err)
# if the file does not exist, will print
# "[Errno 2] No such file or directory: 'mytextfile.txt'"
修改强>
with open("mytextfile.txt", "w") as outf:
outf.write("hello")
相当于
outf = open("mytextfile.txt", "w")
outf.write("hello")
outf.close()
除非确保outf.close()
被调用,即使 outf.write()
导致错误。基本上,它是安全,批准的文件处理方式。
FileNotFoundError
是Python 3的例外,因为找不到文件。如果您使用的是Python 2.7,则会抛出IOError
。