Python基础之文件操作(一)
来源:互联网 发布:qq刷访客软件 编辑:程序博客网 时间:2024/06/05 16:20
一个简单的文件操作的例子
import os;import sys;#set valuecurdir = "";workdir = "E:\\ProgDoc\\python";readfiledir = "readfolder\\readfile.txt";writefiledir = "writefolder\\writefile.txt";readstr = "";#change dircurdir = os.getcwd();os.chdir(workdir);#read from filereadfile = open((readfiledir), "r");for i in range(2):readstr = readfile.readline();readstr = readstr.strip();readstr = "MSG read from readfile: " + readstr + "\n";readfile.close();#write to filewritefile = open((writefiledir), "r");lines = [];for line in writefile:lines.append(line);writefile.close();lines.insert(1, readstr);str = ''.join(lines);writefile = open((writefiledir), "w");writefile.write(str);writefile.close();#resume diros.chdir(curdir);
例子详细说明
1.程序的退出
有两类退出:程序运行时代码中退出,程序运行时终端手动退出。
(1)代码中增加退出语句
exit(); #exit program或
import sys;sys.exit(); #exit program(2)终端手动退出
Ctrl+C
2.目录相关的操作
(1)os.getcwd():获取当前完整路径
(2)os.mkdir(pathstr):创建一个新的目录
(3)os.chdir(pathstr):改变目录到pathstr
(4)os.rmdir(pathstr):删除目录;只能非空
3.文件基本操作
(1)open(filepath [,mode] [, buffering]): 打开文件,模式(r, w, b, +)可选(默认r)
(2)close(): 关闭文件
(3)tell(): 返回文件内的当前位置
(4)seek(offset [, from]): 改变当前的位置(from参考偏移:0->文件头,1->当前位置,2->文件尾)
(5)os.rename(old_filename, new_filename): 重命名文件
(6)os.remove(filepath): 删除文件
(7)read([count]): 读文件,默认时尽可能多
(8)write(str): 写入文件
4.字符串的简单处理函数:strip([chars])
删除字符串中的字符函数,返回处理结果字符串。
声明:s为字符串,rm为要删除的字符序列
s.strip(rm): 删除s字符串中开头、结尾处,位于rm删除序列的字符
s.lstrip(rm): 删除s字符串中开头处,位于rm删除序列的字符
s.rstrip(rm) : 删除s字符串中结尾处,位于rm删除序列的字符
str = '12a 2cd ef12';result = str.strip(); #default ('\n','\r','\t',' ')result = str.strip('12'); #result: a 2cd efresult = str.strip('12 a'); #result: cd ef5.读文件:以行为单位 :readline(), readlines(), for ... in ...
#create file and writefile = open('a.txt', 'w+');file.write("123456.\nabcdef.\nthe third line.");file.close();#read from filefile = open('a.txt', 'r+');#use readline()while 1:line = file.readline();if not line:break;print line;#use readlines()file.seek(0);lines = file.readlines();for line in lines:print line;#use for...in...file.seek(0);for line in file:print line;file.close();注:调用readXXX(),for...in...等读操作后,文件内的位置发生了改变,因此需要使用seek()函数回到文件头位置。
6.字符串的join()函数
用于连接join()中的数据,返回连接结果字符串,例子如下:
#define valuelist = [];str = "first";list.append("first");list.append("second line");list.append("third");result_str = '#'.join(list);#result: first#second line#thirdprint result_str;
- Python基础之文件操作(一)
- python基础之文件操作
- python基础之文件操作
- Python基础学习(一)之切片操作
- python基础学习之文件操作
- Python基础-文件操作
- Python基础-文件操作
- Python文件操作一
- python基础之元组、文件操作、编码、函数、变量
- Python基础之IO文件目录的操作
- 基础之文件操作
- Android基础笔记一之测试与文件操作
- Windows内核编程基础篇之文件操作(一)
- python之文件操作
- python之文件操作
- python 之文件操作
- python 之文件操作
- python之文件操作
- sql取年,月,日技巧,日期转指定格式字符串
- 不错的页面
- 24、25_保存文件到手机内存
- 程序员需要具备的基本技能
- android strict mode
- Python基础之文件操作(一)
- 与dalvik GC相关的属性详解
- ios各种动画效果
- 在iOS开发中使用FMDB
- Range:HTML5中的新型Input类型
- android 遇到的细节 FAQ
- HttpURLConnection 403错误
- 关于oracle with as用法
- ZooKeeper解惑