第一个程序
a =
open('test.txt','w')
a.write('jdhfjkf')
a.write('\n')
a.write('zbvbvxsg')
a.close()
第二个程序
open('test.txt','w').write('jdhfjkf')
open('test.txt','w').write('\n')
open('test.txt','w').write('zbvbvxsg')
open('test.txt','w').close()
我感觉它们应该是一样的。可是为什么只有第一个程序能写入test.txt,而第二个程序的执行结果是空白?
(我想:是不是一个文件只用open和'w'一次,否则,每一次'w' 都会把前面写入的东西清空。可是问题又来了,我把第二个程序第四行去掉,第三行就能写入,可是加上第四行,又变成了空白)这个我懂了
新问题:第一个程序里面,a作为一个变量,也有'w'啊,每次执行a.write()时,不也和第二个程序差不多么?应该也是每write一次,就把前面的清空?
open() returns a file object, and is most commonly used with two arguments: open(filename, mode).>>>>>> f = open('workfile', 'w') >>> print f 写文件有两种模式:一种叫truncate(截断),一种叫append(追加)。前者每次打开文件都会把文件已有的内容删除,再写入内容;后者每次打开文件不会删除已有内容,而是在已有内容之后在写入内容。剩下的题主自己想想?========================================================================学东西,还是好好先找几本书,把基础打好才对。 看文档。 先给出题主提出的新问题的答案,清空内容不是在File Objects 调用write时发生的,而是在用“w”模式open文件时发生的题主其实在两个地方存在疑惑,"w"模式的特性 , 以及file.close的作用 分开说明。关于file.close,Python文档里说的很清楚了,看这里:file.write,我引用一下Due to buffering, the string may not actually show up in the file until the flush() or close() method is called.至于w模式的问题,Python文档并没有把这件事说清,也可能是我没看到:),我在stackoverflow上看到过极好的说明:python open built-in function: difference between modes a, a+, w, w+, and r+?
"w'' Truncate file to zero length or create text file for writing. The stream is positioned at the beginning of the file.我从没见过你这么干的。
def writeFile() : file = open('test.txt','w+') file.write('testtesttest') file.write('\n') file.write('new line') file.close()
open('test.txt','w').write('jdhfjkf') print open('test.txt','r').readlines() open('test.txt','w').write('\n') print open('test.txt','r').readlines() open('test.txt','w').write('zbvbvxsg') print open('test.txt','r').readlines() open('test.txt','w').close()
python怎么学习?python怎么入门?python在哪学?python怎么学才快?不用担心,这里为大家提供了python速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号