python-文件的基本操作
2018-04-11 11:25
691 查看
文件的基本处理
1、打开文件:a、建立磁盘上的文件与程序中的对象相关联。
b、通过相关的文件对象获得。
2、文件操作:读取、写入、定位、追加、计算等。
3、关闭文件:
a、切断文件与程序的联系
b、写入磁盘,并释放文件缓冲区。
4、打开文件:
open():
<variable> = open (<name>,<mode>)
<name> 磁盘文件名
<mode> 打开模式
5、打开模式:
r 只读。 如果文件不存在,则输出错误。 |
w 只写(如果文件不存在,则自动创建文件) 。 |
a 表示附加到文件末尾。 |
rb 只读二进制文件。如果文件不存在,则输出错误。 |
wb 只写二进制文件,如果文件不存在,则自动创建文件。 |
ab 附加到二进制文件末尾。 |
r+ 读写 |
a、打开一个名为 "numbers.dat"的文本文件:
>>>infile = open("numbers.dat","r")
b、打开一个名为 "music.mp3"的音频文件:
>>>infile = open("music.mp3","rb")
7、文件读取:
a、read() 返回值为包含整个文件内容的一个字符串。
b、readline() 返回值为文件下一行内容的字符串。
c、readlines() 返回值为整个文件内容的列表,每项是以换行符为结尾的一行字符串。示例:将文件内容输出到屏幕上
def main():
fname = eval (input("Enter filename: " ))
infile = open(fname,"r")
data = infile.read()
print(data)
main()
举例:输出文件前五行内容 infile = open(someFile, "r") for i in range(5): line = infile.readline() print(line[:-1])
8、写入数据:
<
a64c
p> a、从计算机内存向文件写入数据。 b、write() : 把含有文本数据或二进制数据块的字符串写入文件。
c、writelines():针对列表操作,接受一个字符串列表作为参数,将他们写入文件。举例:写入操作
>>> outfile = open("outfile.txt" , "w")
>>>outfile.writelines(["Hello" , " " , "world"])
>>>outfile.close()
>>>infile = open("outfile.txt" , "r")
>>>infile.read()
'Hello world'
9、遍历文件模板:1、通用代码框架:
file = open(someFile, "r")
for line in file.readlines():
#处理一行文件内容
file.close()
2、简化代码框架:
file = open(someFile, "r")
for line in file:
#处理一行文件内容
file.close()10、文件拷贝:def main():
#用户输入文件名
f1 = input("Enter a souce file: ").strip()
f2 = input("Enter a souce file: ").strip()
#打开文件
infile = open(f1, "r")
outfile = open(f2, "w")
#拷贝数据
countLines = countChars = 0
for line in infile:
countLines += 1
countChars += len(line)
outfile.write(line)
print(countLines, "lines and", countChars, "chars copied")
infile.close()
outfile.close()
main()
相关文章推荐
- python基本文件操作
- Python基础--基本文件操作二
- Python 目录和文件基本操作
- python成长之路第一篇(5)文件的基本操作
- Python基础--基本文件操作二
- Python文件与文件夹常见基本操作总结
- Python基础--基本文件操作
- [python]基本文件操作
- python中文件操作基本流程
- python中文件的基本操作
- python中文件基本操作
- python之文件的基本操作
- Python基本文件操作
- python读写文件基本操作
- Python:文件操作总结1——文件基本操作
- python文件路径的基本操作
- Python基础--基本文件操作
- Python基础--基本文件操作
- Python第四天(基本文件操作二)
- Python 文件基本操作