python文件读写
来源:互联网 发布:java 二叉树分层打印 编辑:程序博客网 时间:2024/06/11 22:29
最基本的文件操作当然就是在文件中读写数据。这也是很容易掌握的。现在打开一个文件以进行写操作:
1. fileHandle = open ( 'test.txt', 'w' )
fileHandle = open ( 'test.txt', 'w' )
‘w'是指文件将被写入数据,语句的其它部分很好理解。下一步就是将数据写入文件:
1. fileHandle.write ( 'This is a test.\nReally, it is.' )
fileHandle.write ( 'This is a test.\nReally, it is.' )
这个语句将“This is a test.”写入文件的第一行,“Really, it is.”写入文件的第二行。最后,我们需要做清理工作,并且关闭文件:
1. fileHandle.close()
fileHandle.close()
正如你所见,在Python的面向对象机制下,这确实非常简单。需要注意的是,当你再次使用“w”方式在文件中写数据,所有原来的内容都会被删除。如果想保留原来的内容,可以使用“a”方式在文件中结尾附加数据:
1. fileHandle = open ( 'test.txt', 'a' )
2. fileHandle.write ( '\n\nBottom line.' )
3. fileHandle.close()
fileHandle = open ( 'test.txt', 'a' )
fileHandle.write ( '\n\nBottom line.' )
fileHandle.close()
然后,我们读取test.txt,并将内容显示出来:
1. fileHandle = open ( 'test.txt' )
2. print fileHandle.read()
3. fileHandle.close()
fileHandle = open ( 'test.txt' )
print fileHandle.read()
fileHandle.close()
以上语句将读取整个文件并显示其中的数据。我们也可以读取文件中的一行:
1. fileHandle = open ( 'test.txt' )
2. print fileHandle.readline() # "This is a test."
3. fileHandle.close()
fileHandle = open ( 'test.txt' )
print fileHandle.readline() # "This is a test."
fileHandle.close()
1. fileHandle = open ( 'test.txt', 'w' )
fileHandle = open ( 'test.txt', 'w' )
‘w'是指文件将被写入数据,语句的其它部分很好理解。下一步就是将数据写入文件:
1. fileHandle.write ( 'This is a test.\nReally, it is.' )
fileHandle.write ( 'This is a test.\nReally, it is.' )
这个语句将“This is a test.”写入文件的第一行,“Really, it is.”写入文件的第二行。最后,我们需要做清理工作,并且关闭文件:
1. fileHandle.close()
fileHandle.close()
正如你所见,在Python的面向对象机制下,这确实非常简单。需要注意的是,当你再次使用“w”方式在文件中写数据,所有原来的内容都会被删除。如果想保留原来的内容,可以使用“a”方式在文件中结尾附加数据:
1. fileHandle = open ( 'test.txt', 'a' )
2. fileHandle.write ( '\n\nBottom line.' )
3. fileHandle.close()
fileHandle = open ( 'test.txt', 'a' )
fileHandle.write ( '\n\nBottom line.' )
fileHandle.close()
然后,我们读取test.txt,并将内容显示出来:
1. fileHandle = open ( 'test.txt' )
2. print fileHandle.read()
3. fileHandle.close()
fileHandle = open ( 'test.txt' )
print fileHandle.read()
fileHandle.close()
以上语句将读取整个文件并显示其中的数据。我们也可以读取文件中的一行:
1. fileHandle = open ( 'test.txt' )
2. print fileHandle.readline() # "This is a test."
3. fileHandle.close()
fileHandle = open ( 'test.txt' )
print fileHandle.readline() # "This is a test."
fileHandle.close()
- python--python读写文件
- Python读写Unicode文件
- python Ini文件读写
- Python读写文件
- Python读写文件
- Python读写ini文件
- Python读写文件
- Python读写文件
- Python文件的读写
- python读写文件
- python文件读写
- [Python]读写文件方法
- python 文件读写操作
- Python文件读写操作
- Python读写文件
- python之读写文件
- python读写文件
- python文件的读写
- 求水仙花数(0-1000) C/C++
- Ubuntu下如何关闭ThinkPad触摸板而不禁用触点
- js特殊字符的过滤
- 内核的bootmem内存分配器
- #pragma once 用法含意
- python文件读写
- python 输入系统参数
- '_beginthreadex' : undeclared identifier
- setup 命令安装
- Z-Wave System Startup
- 【转】java序列化机制和原理
- A problem is easy
- zoj 3261 Connections in Galaxy War(逆向并查集)
- 编程之美--链表是否相交