2013-01-19 53 views
0

我的代码:'打开()'不起作用?

filename = "C:/users/patrik/documents/mypython.txt" 
with open(filename) as f: 
    if f.readlines()[0] == "patrik's file": #first line 
     f.write("This file has been read by patrik!") 

为什么它不工作?我没有收到任何错误,此后文件内容变得杂乱,我做错了什么?

+1

它以什么方式不起作用? – BrenBarn

+0

文件内容变得非常混乱,每次看起来都不一样,它有一些奇怪的字符,我不能在这里粘贴... –

+1

当你说“没有错误”,你的意思是'AttributeError:'str'对象没有任何属性“readlines''? – Eric

回答

2

要执行读取和写文件操作就可以选择这些模式之一:

'r+'

Opens a file for both reading and writing. The file pointer will be at the beginning of the file.

'a+'

Opens a file for both appending and reading. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing.

注意file是一个内嵌函数在python中,所以你不应该用它作为变量名称

+0

另外'''file'''是一个Python内建的,使用另一个变量名。 – ismail

+0

呃抱歉在我的实际脚本中有'f'!如果我也想阅读它,我必须打开它两次吗? –

+2

他应该用'r +'模式打开文件。读和写。 'w'将首先清除*文件。 –

相关问题