文件

文件和文件夹

文件:文本文件、二进制文件

文件夹:(windows) G:\pythonWorkspace\python\study

    (linux/mac) /home/workspace/python

    注意:文件夹路径的斜杠linux与windows不同

windows下文件路径:示例 

 >>> p1="G:\pythonWorkspace\python\study\test.txt"
>>> p2 =r"G:\pythonWorkspace\python\study\test.txt"
>>> p3 ="G:\\pythonWorkspace\\python\\study\\test.txt"

跨平台路径:os.path.abspath(path)

查看属性:os.stat(filename)


p2 =r"G:\pythonWorkspace\python\study\test.txt"
 >>> import os #引入os 模块
 >>> os.stat(p2) #查看文件属性  nt.stat_result(st_mode=33206, st_ino=0L, st_dev=0L, st_nlink=0, st_uid=0, st_gid=0, st_size=14L, st_atime=1520953379L, st_mtime=1520953401L, st_ctime=1520953379L)  >>>

读、写文件

python 中文件也是一种类型的对象,有属性 __iter__,说明是可迭代的

打开一个文件

>>> dir(file)  #查看文件的属性
['__class__', '__delattr__', '__doc__', '__enter__', '__exit__', '__format__', '__getattribute__', '__hash__', '__init__', '__iter__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'close', 'closed', 'encoding', 'errors', 'fileno', 'flush', 'isatty', 'mode', 'name', 'newlines', 'next', 'read', 'readinto', 'readline', 'readlines', 'seek', 'softspace', 'tell', 'truncate', 'write', 'writelines', 'xreadlines']
>>> f =open(p2) #打开一个文件
>>> for line in f: #循环读取文件内容
... print line #打印出来后,两行之间有空行,原因print 会自动的带上一个换行符
...
study python aaaaa >>> f =open(p2) #第二次也要open文件
>>> for line in f:
... print line, #出现空行解决方式在line后面加,
...
study python
aaaaa
>>>

写文件

w 模式 打开一个文件只用于写入。如果该文件已存在则将其覆盖。如果该文件不存在,创建新文件

a 模式 打开一个文件用于追加。如果该文件已存在,文件指针将会放在文件的结尾。也就是说,新的内容将会被写入到已有内容之后。如果该文件不存在,创建新文件进行写入。

with 语句 可以不写close()

 >>> nf =open("G:\\pythonWorkspace\\python\\study\\test.txt","w") #打开一个文件,用w模式,写入
>>> nf.write("This is a new file.") #将这句话写入文件
>>> nf.close() #打开一个文件,写入后必须关闭掉
>>> nf =open("G:\\pythonWorkspace\\python\\study\\test.txt")
>>> for line in nf:
... print line
...
This is a new file.
 >>> with open("G:\\pythonWorkspace\\python\\study\\test.txt","a") as fp:  #with open 也可以创建文件 打开文件,适用with open write后面的close()可以不写,它会自动处理
... fp.write("\n what's your name?")
... >>> f =open("G:\\pythonWorkspace\\python\\study\\test.txt")
>>> for line in f:
... print line
... what's your name?
>>>

不同的读文件方法

 >>> help(file.read)
Help on method_descriptor:
  #参数size可选,如果没有参数,将文件的全部内容读取,如果有参数,将读取到指定的字节,然后将读取到的这些内容以字符串形式返回
所读取的内容一次返回到内存中,随时可以取用,方便快捷。这种方式,如果文件特别大的时候,会使内存开销太大。
read(...)
read([size]) -> read at most size bytes, returned as a string. If the size argument is negative or omitted, read until EOF is reached.
Notice that when in non-blocking mode, less data than what was requested
may be returned, even if no size parameter was given. >>> help(file.readline)
Help on method_descriptor:
参数(size)可选,它是以行为单位返回一个字符串,每次读取一行,依次循环往下读取,如果没有参数,则将读取到文件最后,返回空字符串,到达文件末尾。END OF FILE (EOF)
readline(...)
readline([size]) -> next line from the file, as a string. Retain newline. A non-negative size argument limits the maximum
number of bytes to return (an incomplete line may be returned then).
Return an empty string at EOF. >>> help(file.readlines)
Help on method_descriptor:
返回以行为单位的列表,相当于执行readline, 得到每一行,然后把这一行的字符串,作为列表中的元素,再放到一个列表中,最后将列表返回。
readlines(...)
readlines([size]) -> list of strings, each a line from the file. Call readline() repeatedly and return a list of the lines so read.
The optional size argument, if given, is an approximate bound on the
total number of bytes in the lines returned.

示例:读取文件

  read()      读取文件内容,如果指定参数,将指定字节相应的内容返回,如果没有指定参数,将文件内容全部返回。

  readline() 以行为单位读取文件,返回一个字符串,每次读取一行,一次循环往下读取。如果没有指定参数,将读取到文件末尾。

  readlines() 返回以行为单位的列表,相当于执行readline,得到每一行,然后把这一行的字符串,作为列表的元素,最后将这个列表返回

  import fileinput 读取大文件时,使用

  f.seek(0) 改变当前文件的位置

  f.tell() 告诉文件当前的指针位置,文件内的当前位置

 >>> f =open("G:\\pythonWorkspace\\python\\study\\test.txt")
>>> c=f.read() #把文件的全部内容读取出来,放到一个变量
>>> c
"\n what's your name?"
>>> f =open("G:\\pythonWorkspace\\python\\study\\test.txt")
>>> f.read(5) #有参数,将返回相应字节的内容
'\n wha'
>>> f =open("G:\\pythonWorkspace\\python\\study\\test.txt")
>>> f.readline() 返回第一行的内容,每一行都是一个字符串
'\n'
>>> f =open("G:\\pythonWorkspace\\python\\study\\test.txt")
>>> f.readlines() 返回一个列表,列表中每一行为一个元素
['\n', " what's your name?"]
>>> import fileinput #引入大文件模块,避免文件太大,内存过满的问题
>>> for line in fileinput.input("G:\\pythonWorkspace\\python\\study\\bigfile.txt"):
... print line
...
Before getting started, you may want to find out which IDEs and text editors are tailored to make Python editing easy, browse the list of introductory books, or look at code samples that you might find helpful. There is a list of tutorials suitable for experienced programmers on the BeginnersGuide/Tutorials page. There is also a list of resources in other languages which might be useful if English is not your first language.
>>> f=open("G:\\pythonWorkspace\\python\\study\\bigfile2.txt")
>>> for line in f:
... print line
...
Before getting started, you may want to find out which IDEs and text editors are tailored to make Python editing easy, browse the list of introductory books, or look at code samples that you might find helpful. There is a list of tutorials suitable for experienced programmers on the BeginnersGuide/Tutorials page. There is also a list of resources in other languages which might be useful if English is not your first language.
  #每次读取完一个文件之后,都需要重新把这个文件再打开一次,之所以这样做是因为指针已经移到文件最后了。
>>> f.seek(0) #使用seek()移动指针,参数0为,指针回到文件最开始,
>>> f.readline()
'Before getting started, \n'
>>> f.tell() #使用tell()查看当前指针的位置
26L
>>> f.seek(4) #参数为4,将指针定位到从开头到第4个字符的位置的后面
>>> f.tell()
4L
>>>

Python 学习笔记(十二)Python文件和迭代(一)的更多相关文章

  1. python3.4学习笔记(十二) python正则表达式的使用,使用pyspider匹配输出带.html结尾的URL

    python3.4学习笔记(十二) python正则表达式的使用,使用pyspider匹配输出带.html结尾的URL实战例子:使用pyspider匹配输出带.html结尾的URL:@config(a ...

  2. Python学习笔记(十二)—Python3中pip包管理工具的安装【转】

    本文转载自:https://blog.csdn.net/sinat_14849739/article/details/79101529 版权声明:本文为博主原创文章,未经博主允许不得转载. https ...

  3. Python学习笔记之二——Python的运行机制,一般人肯定不会

    前言本文的文字及图片来源于网络,仅供学习.交流使用,不具有任何商业用途,版权归原作者所有,如有问题请及时联系我们以作处理.作者:XX   Python解释器简介   解释器是一种让其他程序运行起来的程 ...

  4. python 学习笔记(十二) 文件和序列化

    python 文件读写和序列化学习.## python文件读写`1 打开并且读取文件` f = open('openfile.txt','r') print(f.read()) f.close() ` ...

  5. python学习笔记(二)文件操作和集合

    集合: 集合也是一种数据类型,一个类似列表东西,它的特点是无序的,不重复的,也就是说集合中是没有重复的数据 集合的作用: 1.它可以把一个列表中重复的数据去掉,而不需要你再写判断 2.可以做关系测试, ...

  6. python 学习笔记十二 html基础(进阶篇)

    HTML 超级文本标记语言是标准通用标记语言下的一个应用,也是一种规范,一种标准,它通过标记符号来标记要显示的网页中的各个部分.网页文件本身 是一种文本文件,通过在文本文件中添加标记符, 可以告诉浏览 ...

  7. python学习笔记(十二)-网络编程

    本文结束使用 Requests 发送网络请求.requests是一个很实用的Python HTTP客户端库,编写爬虫和测试服务器响应数据时经常会用到.可以说,Requests 完全满足如今网络的需求. ...

  8. Python学习笔记十二

    HTML全称:Hyper Text Markup Language超文本标记语言 不是编程语言 HTML使用标记标签来描述网页 2.  HTML标签 开始标签,结束标签.  例如:<html&g ...

  9. python学习笔记(十 二)、操作数据库

    每一种语言都少不了多数据库进行各种操作. python支持多种数据库.有关python支持的数据库清单,请参阅:https://wiki.python.org/moin/DatabaseInterfa ...

  10. python学习笔记十二:类的定义

    demo #!/usr/bin/python class Person: name = 'jim' age = 25 def say(self): print 'My name is ' + self ...

随机推荐

  1. v-model的双向数据绑定(表单)

    可以用 v-model 指令在表单 <input>.<textarea> 及 <select> 元素上创建双向数据绑定.它会根据控件类型自动选取正确的方法来更新元素 ...

  2. framework7的改进,以及与vue组合使用遇到的问题以及解决方法 (附vue的原理)

    framework7官方提供了vue+framework7的组合包,但是那个包用起来复杂度较高,而且不灵活.听说bug也不少. 所以我想用最原始的方式单独使用vue和framework7. 遇到以下问 ...

  3. 前端学习之路之CSS (二)

    Infi-chu: http://www.cnblogs.com/Infi-chu/ id选择器id 选择器可以为标有特定 id 的 HTML 元素指定特定的样式,CSS 中 id 选择器以 &quo ...

  4. vscode 快速生成html

    在Hbuilder中新建一个htm自动会生成一个标准的html代码,那在vscode得一行一行写吗?太烦了吧,各种关键词搜,哎妈 终于找到了办法,现在这里记录下: 第一步:在空文档中输入   ! 第二 ...

  5. Windows操作系统----锁住命令行窗口

    第一步: 新建一个.txt文档,输入如下内容: @echo off echo. setlocal :checkpassword set /p password=请输入密码: if "%pas ...

  6. IsWindow,findwindow

    原文:http://www.cnblogs.com/ahuo/archive/2007/12/05/983354.html IsWindow 函数功能:该函数确定给定的窗口句柄是否识别一个已存在的窗口 ...

  7. C# 中重载自增自减操作符的具体运算原理 ----从C++程序员的角度看C#自增操作符重载的实质

    看了看C#的运算符重载,发现与C++打不相同.刚刚被C#的自增操作符坑了,现在来分享一下. 先定义一个类 class A { public int i; public A(int I) { i = I ...

  8. centos 开机执行的命令

    centos开机执行的命令-------待验证,因为有可能涉及到root问题,没想明白怎么输入密码 1.增加rc.local可执行权限 chmod +x /etc/rc.d/rc.local 2.在里 ...

  9. linux 文件常用操作

    linux 文件基本操作 新建文件:touch test 不会替换重名文件,并且linux一切都是文件,文件夹和文件不能重名 新建文件夹:mkdir test使用 -p 参数,同时创建父目录(如果不存 ...

  10. FZEasyFile的使用

    FZEasyFile的使用 https://github.com/jiecao-fm/FZEasyFile 操作沙盒文件很恶心,但用上FZEasyFile就变得简单了. 以前你需要这么做才行: NSF ...