Python基础之文件操作(一)

一个简单的文件操作的例子

import os;
import sys;

#set value
curdir = "";
workdir = "E:\\ProgDoc\\python";
readfiledir = "readfolder\\readfile.txt";
writefiledir = "writefolder\\writefile.txt";
readstr = "";

#change dir
curdir = os.getcwd();
os.chdir(workdir);

#read from file
readfile = 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 file
writefile = 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 dir
os.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 ef
result = str.strip('12 a');  #result: cd ef
5.读文件:以行为单位 readline(), readlines(), for ... in ...

#create file and write
file = open('a.txt', 'w+');
file.write("123456.\nabcdef.\nthe third line.");
file.close();

#read from file
file = 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 value
list = [];
str = "first";

list.append("first");
list.append("second line");
list.append("third");

result_str = '#'.join(list);

#result: first#second line#third
print result_str;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值