文件学习笔记(Python)

文件

1、  持久化

持久化(persistent):程序的一种属性,它会一直的运行,并至少保存一部分数据在永久存储中。

文本文件是存储在诸如硬盘、闪存或光盘的永久媒介上的字符串序列。

 

2、  读和写

要写入一个文件,需要用’w’模式作为第二个实参打开它。

import os

os.chdir("C:/Users/hhxsym/Desktop/python.workspace/dir")#指定目录

os.getcwd() #查看目录

 

In [167]: fout=open('output.txt','w')

 

In [168]: print fout

<open file 'output.txt', mode 'w' at0x0000000009B98AE0>

 

In [169]: line1="This here's thewattle, \n"

 

In [170]: fout.write(line1)

 

In [171]: line2="the element of ourland.\n"

 

In [172]: fout.write(line2)

 

In [173]: fout.close()

 

(1)      如果文件存在,使用写模式打开,会清掉旧有的数据重新开始,要谨慎!

(2)      write再次调用时,它会从结尾处添加新的数据。

(3)      当写入完毕时,需要关闭文件。

3、  格式操作符

write的参数必须时字符串,所有我们要想往文件中写入其它类型的值,必须将他们先转化为字符串。

(1)      最容易的方法就是使用str.

In [174]: fout=open('output.txt','w')

In [175]: x=52

In [176]: fout.write(x)

Traceback (most recent calllast):

File "<ipython-input-176-6a1e2656a10e>", line 1,in <module>

fout.write(x)

 

TypeError: expected a string or other character buffer object

In [177]: fout.write(str(x))

In [178]: fout.close()

(2)      另一个方法是格式操作符%

当用于整数时,%是求余操作符;但当第一个操作对象是字符串时,%则是格式操作符。

%的第一个操作对象是格式字符串,包括一个或多个格式序列。由他们指定第二个操作对象如何格式化,表达式的结果是一个字符串。

In[183]: camels=42

 

In[184]: '%d'%camels

Out[184]: '42'

(1)      格式字符串可以在字符串的任意地方,所以,你可以在一个句子中嵌入变量值;

(2)      如果字符串多余一个格式序列,第二个操作对象就必须是元祖,每个格式按顺序对应元祖的一个元素。

4、文件名和路径

os模块提供了用于操作文件和目录的函数。

(1)  os.getcwd()返回当前目录;os.chidir(path)改变当前目录;

(2)  os.path.abspathfilename)来找寻文件的绝对路径

 

In[189]:os.chdir("C:/Users/hhxsym/Desktop/python.workspace") #指定目录

In[190]: os.listdir(os.getcwd())

Out[190]:

['dir',

'dir1',

'dir2',

'file1.txt',

'file2.txt',

'~$\xba\xaf\xca\xfd\xd1\xa7\xcf\xb0\xb1\xca\xbc\xc7(python).docx',

'~$\xd1\xa7\xcf\xb0\xb1\xca\xbc\xc7\xa3\xa8python\xa3\xa9.docx',

'~WRL0005.tmp',

'~WRL2430.tmp',

'\xce\xc4\xbc\xfe\xd1\xa7\xcf\xb0\xb1\xca\xbc\xc7\xa3\xa8python\xa3\xa9.docx',

'\xc0\xe0\xd3\xeb\xba\xaf\xca\xfd\xd1\xa7\xcf\xb0\xb1\xca\xbc\xc7(python).docx',

'\xc0\xe0\xd3\xeb\xb6\xd4\xcf\xf3\xd1\xa7\xcf\xb0\xb1\xca\xbc\xc7(python).docx',

'\xc0\xe0\xba\xcd\xb7\xbd\xb7\xa8\xd1\xa7\xcf\xb0\xb1\xca\xbc\xc7(Python).docx']

 

In[191]: os.path.abspath('dir1')

Out[191]: 'C:\\Users\\hhxsym\\Desktop\\python.workspace\\dir1'

 

In[192]: os.path.abspath('file1.txt')

Out[192]: 'C:\\Users\\hhxsym\\Desktop\\python.workspace\\file1.txt'

 

(3)os.path.exists(filenameor dirname)检查一个文件或目录是否存在

 

In[191]: os.path.abspath('dir1')

Out[191]: 'C:\\Users\\hhxsym\\Desktop\\python.workspace\\dir1'

 

In[192]: os.path.abspath('file1.txt')

Out[192]: 'C:\\Users\\hhxsym\\Desktop\\python.workspace\\file1.txt'

 

In[193]: os.path.exists('dir1')

Out[193]: True

 

In[194]: os.path.exists('dir3')

Out[194]: False

 

In[195]: os.path.exists('file1.txt')

Out[195]: True

 

In[196]: os.path.exists('file3.txt')

Out[196]: False

(4)os.path.isdir(dirname)检查它是否为目录; os.path.isfile(filename)检查它是否为文件

In[197]: os.path.isdir('dir1')

Out[197]: True

 

In[198]: os.path.isfile('dir1')

Out[198]: False

 

In[199]: os.path.isdir('file1.txt')

Out[199]: False

 

In[200]: os.path.isfile('file1.txt')

Out[200]: True

(5)os.listdir(path)返回指定目录中的文件以及其它目录的列表

In[201]: cwd=os.getcwd()

 

In[202]: os.listdir(cwd)

Out[202]:

['dir',

'dir1',

'dir2',

'file1.txt',

'file2.txt',

'~$\xba\xaf\xca\xfd\xd1\xa7\xcf\xb0\xb1\xca\xbc\xc7(python).docx',

'~$\xd1\xa7\xcf\xb0\xb1\xca\xbc\xc7\xa3\xa8python\xa3\xa9.docx',

'~WRL0005.tmp',

'~WRL2430.tmp',

'\xce\xc4\xbc\xfe\xd1\xa7\xcf\xb0\xb1\xca\xbc\xc7\xa3\xa8python\xa3\xa9.docx',

'\xc0\xe0\xd3\xeb\xba\xaf\xca\xfd\xd1\xa7\xcf\xb0\xb1\xca\xbc\xc7(python).docx',

'\xc0\xe0\xd3\xeb\xb6\xd4\xcf\xf3\xd1\xa7\xcf\xb0\xb1\xca\xbc\xc7(python).docx',

'\xc0\xe0\xba\xcd\xb7\xbd\xb7\xa8\xd1\xa7\xcf\xb0\xb1\xca\xbc\xc7(Python).docx']

 

1:需要提取目录下的文件,目录是中文名字不太方便,如何打印中文名。

解决办法:使用unicode()对路径进行处理

修改前:

# encoding=utf-8

os.chdir("C:/Users/hhxsym/Desktop/python.workspace")#指定目录

cwd=os.getcwd()

#cwd=unicode(cwd, 'utf-8') #处理后

dirs=os.listdir(cwd)

for dir in dirs:

    print dir

输出:

dir

dir1

dir2

file1.txt

file2.txt

~$ѧϰʼǣpython��.docx

ļѧϰʼǣpython��.docx

�����ѧϰʼ(python).docx

�������ѧϰʼ(python).docx

��ͷ���ѧϰʼ(Python).docx

 

处理后:

# encoding=utf-8

os.chdir("C:/Users/hhxsym/Desktop/python.workspace")#指定目录

cwd=os.getcwd()

cwd=unicode(cwd,'utf-8') #处理后

dirs=os.listdir(cwd)

for dir in dirs:

print dir

输出:

dir

dir1

dir2

file1.txt

file2.txt

~$学习笔记(python.docx

文件学习笔记(python.docx

类与函数学习笔记(python).docx

类与对象学习笔记(python).docx

类和方法学习笔记(Python).docx

 

 

 

2Python直接读取中文路径的文件时失败,可做如下处理

"path"经过编码后的路径去open()即可:

 

step1: 原始代码

In[298]:inpath='C:/Users/hhxsym/Desktop/python.workspace/中文文件名.txt'

     ...: #inpath = unicode(inpath , "utf8") #或者 utf-8

     ...: fin=open(inpath)

     ...:

     ...:

Traceback (most recent call last):

 

File"<ipython-input-298-1c27a31be063>", line 3, in <module>

fin=open(inpath)

 

IOError: [Errno 22] invalid mode ('r') or filename:'C:/Users/hhxsym/Desktop/python.workspace/\xe4\xb8\xad\xe6\x96\x87\xe6\x96\x87\xe4\xbb\xb6\xe5\x90\x8d.txt'

 

step2:改进代码,python 读取中文文件名/中文路径

inpath='C:/Users/hhxsym/Desktop/python.workspace/中文文件名.txt'

inpath = unicode(inpath , "utf8")  #"path"经过编码后路径去open()即可,或者 utf-8

fin=open(inpath)

for i in fin.readlines():

    print i

fin.close

 

hello,world!

 

��ã��й

Out[315]: <function close>

 

stage3:如何读取文件中的中文

inpath='C:/Users/hhxsym/Desktop/python.workspace/中文文件名.txt'

inpath = unicode(inpath , "utf-8")

fin=open(inpath)

for i in fin.readlines():

    print i.decode('gbk')

fin.close

 

输出:

hello,world!

 

你好!中国

Out[319]: <function close>

 

3:走遍一个目录,打印所有的文件名称,并对之中的子目录进行递归调用。

import os

os.chdir("C:/Users/hhxsym/Desktop/python.workspace")#指定目录

cwd=os.getcwd()

cwd=unicode(cwd,'utf8') #处理后,可以处理含中文的文件名,否则会出现

#乱码

def walk(dirname):

    for name inos.listdir(dirname):

       path=os.path.join(dirname, name)

       

        ifos.path.isfile(path):

            printpath

        else:

           walk(path)

输出:

  ...: walk(cwd)

C:\Users\hhxsym\Desktop\python.workspace\dir\output.txt

C:\Users\hhxsym\Desktop\python.workspace\dir1\qw.txt

C:\Users\hhxsym\Desktop\python.workspace\dir2\wq.txt

C:\Users\hhxsym\Desktop\python.workspace\file1.txt

C:\Users\hhxsym\Desktop\python.workspace\file2.txt

C:\Users\hhxsym\Desktop\python.workspace\中文文件名.txt

C:\Users\hhxsym\Desktop\python.workspace\文件学习笔记(python).docx

C:\Users\hhxsym\Desktop\python.workspace\类与函数学习笔记(python).docx

C:\Users\hhxsym\Desktop\python.workspace\类与对象学习笔记(python).docx

C:\Users\hhxsym\Desktop\python.workspace\类和方法学习笔记(Python).docx

 

其中,os.path.join接收一个目录和一个文件名称,并将他们拼接未一个完整的路径。

In [2]: import os

 

In [3]: os.path.join('c:ad', 'file.txt')

Out[3]: 'c:ad\\file.txt'

 

5、捕获异常

try:

   inpath='C:/Users/hhxsym/Desktop/python.workspace/中文文件名1.txt'

    inpath =unicode(inpath , "utf-8")

    fin=open(inpath)

    for i infin.readlines():

        printi.decode('gbk')

    fin.close()

except:

    print "something went wrong"

6、数据库

数据库是一个有组织的数据文件,大部分数据库都像字典一样组织数据,因为他们也将键映射到值上。

7、封存

pickle可以将几乎所有的类型的对象转换为适合保存到数据库的字符串形式,并可以将字符串转换回来成为对象。

1:新对象和旧有对象值相同,但通常不是同一个对象

import pickle

t=[1,2,3]

s=pickle.dumps(t)

s

Out[24]: '(lp0\nI1\naI2\naI3\na.'

t1=pickle.loads(s)

t1

Out[26]: [1, 2, 3]

 

t == t1

Out[27]: True

t is t1

Out[28]: False

2:存储在本地

import pickle

fin=open('mydata.pickle', 'wb')

pickle.dump([1,2,'abc'],fin)  #存储在本地

fin.close()

3:存储在本地

import pickle

with open('mydata.pickle', 'wb') as mysavedata:

pickle.dump([1,2,'three'], mysavedata)

8、管道

任何字符界面启动的程序都可以在python中通过一个管道(pipe)来启动,管道代表一个正在运行的程序对象。如:

Unix命令ls –l 展示当前目录的内容,可以使用os.popen来启动ls:

>>>cmd=’ls-l’

>>>fp=os.popen(cmd)

>>>res=fp.read()#读取所有输出

>>>stat=fp.close()#关闭

>>>print stat#查看状态

 

9、编写模块

# -*- coding: utf-8 -*-

import os

def linecount(filename):

    count=0

    for line inopen(filename):

        count += 1

    return count

#print linecount(inpath)

 

if __name__=='__main__':

   inpath='C:/Users/hhxsym/Desktop/python.workspace/中文文件名.txt'

    inpath =unicode(inpath , "utf-8")

    printlinecount(inpath)

print '测试程序'

 

这个例子唯一的问题是当你导入模块时,它会执行底部的测试代码。正常情况下,当你导入一个模块时,他会定义新的函数,但不会执行。

其中,__name__是一个内置变量,当程序启动时,就会被设置。

(1)  如果程序作为脚本执行,__name__的值是__main__,此时,测试代码会被执行;

(2)  否则,如果程序作为模块被导入,则测试代码就被跳过。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值