python 文件操作

#open(路径+文件名,读写模式)

from:http://hi.baidu.com/zzfxz/blog/item/1c4d73cb4aa2c814bf09e613.html

f=open('/tmp/hello','w')

#读写模式:r只读,r+读写,w新建(会覆盖原有文件),a追加,b二进制文件.常用模式

读写模式的类型有:

rU 或 Ua 以读方式打开, 同时提供通用换行符支持 (PEP 278)
w     以写方式打开,
a     以追加模式打开 (从 EOF 开始, 必要时创建新文件)
r+     以读写模式打开
w+     以读写模式打开 (参见 w )
a+     以读写模式打开 (参见 a )
rb     以二进制读模式打开
wb     以二进制写模式打开 (参见 w )
ab     以二进制追加模式打开 (参见 a )
rb+    以二进制读写模式打开 (参见 r+ )
wb+    以二进制读写模式打开 (参见 w+ )
ab+    以二进制读写模式打开 (参见 a+ )

注意:

1、使用'W',文件若存在,首先要清空,然后(重新)创建,

2、使用'a'模式 ,把所有要写入文件的数据都追加到文件的末尾,即使你使用了seek()指向文件的其他地方,如果文件不存在,将自动被创建。


f.read([size]) size未指定则返回整个文件,如果文件大小>2倍内存则有问题.f.read()读到文件尾时返回""(空字串)

file.readline() 返回一行

file.readline([size]) 返回包含size行的列表,size 未指定则返回全部行

for line in f: print line #通过迭代器访问

f.write("hello\n") #如果要写入字符串以外的数据,先将他转换为字符串.

f.tell() 返回一个整数,表示当前文件指针的位置(就是到文件头的比特数).

f.seek(偏移量,[起始位置])

用来移动文件指针

偏移量:单位:比特,可正可负

起始位置:0-文件头,默认值;1-当前位置;2-文件尾

f.close() 关闭文件

Code:


#!/usr/bin/env python
# Filename: using_file.py

poem='''\Programming is funWhen the work is doneif you wanna make your work also fun: use Python!'''
f=file('poem.txt','w') # open for 'w'riting
f.write(poem) # write text to file
f.close() # close the file
f=file('poem.txt')

# if no mode is specified, 'r'ead mode is assumed by default
while True: 
line=f.readline() 
if len(line)==0: # Zero length indicates EOF 
break 
print line, 
# Notice comma to avoid automatic newline added by Python
f.close() 
# close the file


Python 文件重命名

#coding=utf-8  
  
import os
path = '/opt/fish/'
count = 1
for file in os.listdir(path):
    os.rename(os.path.join(path,file),os.path.join(path,str(count)+".jpg"))
    count+=1

Python读取一个文本文件,删除文本文件的空行代码如下:

def  delblankline(infile, outfile):
     """ Delete blanklines of infile """
     infp  =  open (infile,  "r" )
     outfp  =  open (outfile,  "w" )
     lines  =  infp.readlines()
     for  li  in  lines:
         if  li.split():
             outfp.writelines(li)
     infp.close()
     outfp.close()
if  __name__  = =  "__main__" :
     delblankline( "1.txt" , "2.txt" )

  1. Python中换行符为"\n";

  2. Python中操作换行符的函数为:replace("\n",""),替换函数;

  3. 步骤:先判断读取文件,判断每一行是不是只包含换行符:

    如果是,则直接删除;

    如果不是,则用replace("\n","")替换所有换行符,并在最后加一个换行符。

  4. 代码如下:

fpa = open ( "dll.txt" , "r" )
fpb = open ( "dllNew.txt" , "w" )
for  linea  in  fpa.readlines():
     lineb = linea.replace( "\n" ,"")
     if  lineb  = =  "":
         print  "Blank !"
     else :
         fpb.write(linea)
fpa.close()
fpb.close()

一、去除空格

  strip()

"   xyz   ".strip() # returns "xyz"  " xyz ".lstrip() # returns "xyz "  " xyz ".rstrip() # returns " xyz"  " x y z ".replace(' ', '') # returns "xyz" 

二、替换 replace("space","")

  用replace("\n", ""),后边的串替换掉前边的

python实现将文件夹内所有txt文件合并成一个文件


#coding=utf-8 
import os
#获取目标文件夹的路径
filedir = os.getcwd()+'/yuliao'
#获取当前文件夹中的文件名称列表  
filenames=os.listdir(filedir)
#打开当前目录下的result.txt文件,如果没有则创建
f=open('result.txt','w')
#先遍历文件名
for filename in filenames:
    filepath = filedir+'/'+filename
    #遍历单个文件,读取行数
    for line in open(filepath):
        f.writelines(line)
    f.write('\n')
#关闭文件
f.close()




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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值