"""提示:代码中的内容均被注释,请参考,切勿照搬"""

  1 #文件的打开和关闭
'''
文件对象 = open('文件名','使用方式')
rt:读取一个txt文件
wt: 只写打开一个txt文件,(如果没有该文件则新建该文件)会覆盖原有内容
at:打开一个txt文件,并从文件指针位置追加写内容(文件指针默认在末尾)
文件操作错误属于:I/O异常
通常的异常:
try:
f = open('a.txt','wt')
except Exception as e:
print(e)
'''
#文件的写操作
# 函数: 文件对象.write(s)其中s是待写入文件的字符串{文件对象需要时可写入的对象}
'''
try:
fobj = open('anc.txt','wt') #wt:可写入操作方式/at为在原有的文件内容追加写入
fobj.write('\nmore') #写函数
fobj.close() except Exception as err:
print(err) 结果:anc文件保存至当前目录下,并写入“[换行]more”
'''
#案例:学生信息储存
'''
name = 'wanzi'
gender = '男'
age = 23
try:
f = open('students.txt','wt')
while True:
#s = Student(i)
#if s:
f.write("namegenderge")
ans = input("continue(Y/y):")
if ans != 'Y' and ans != 'y':
break
i = i+1
f.close() except Exception as e:
print(e) '''
#读文件操作 文件对象.read(n) //返回全部字符串或者n字节字符
'''
def writeFile(): #写文件操作
f = open('abc.txt','wt')
f.write("Hello world\nI am Code_boy\nMirror_") #三行数据(两个\n)
f.close() def readFile(): #读文件操作
f = open('abc.txt','rt')
sread = f.read() #文件内容读取 [如果read(n)有值,则读取n个字符,为空则读取全部]
print(sread) #将读取的内容打印输出
f.close() try:
writeFile() #调用写文件函数,写入文件
readFile() #调用读文件函数,读出(打印)文件内容
except Exception as e:
print(e) ''''''
结果:
Hello world
I am Code_boy
Mirror_
'''
#读文件操作 文件对象.readline() //返回一行字符串(读取连续的字符串,遇到\n或文件末尾结束)
'''
def writeFile():
f = open('readline.txt','wt')
f.write('Hello\nworld')
f.close() def readlineFile():
f = open('readline.txt','rt')
sreadline = f.readline() #读取readline文件(只读一行)
print(sreadline,'len=',len(sreadline))
sreadline = f.readline()
print(sreadline, 'len=', len(sreadline))
sreadline = f.readline()
print(sreadline, 'len=', len(sreadline)) f.close()
try:
writeFile()
readlineFile()
except Exception as e:
print(e) 结果:
Hello #readline中的文件内容: Hello\nworld 结合readline的功能,在读取一行的数据
len= 6 # ‘Hello\n’ >>>> 共计6个字节(换行是因为读取了\n)
world len= 5 #如上类说明
len= 0 #文件指针已到达末尾,无法继续读出数据故 len = 0 '''
# .readline()可以使用循环的方式(判断是否读取为空)来读取全部,一般都是使用读单行内容
#但是! .readlines(){加了一个‘s'}就可以直接读取全部数据:
'''
def writeFile():
f = open('readline.txt','wt')
f.write('Hello\nworld')
f.close() def readlinesFile():
f = open('readline.txt','rt')
sreadlines = f.readlines() #读取readlines文件(读全部行)并以list形式返回
#因为是以列表格式返回,所以一般情况下会配合循环(for)从readlines()提取每一行循环打印输出
for i in range(len(sreadlines)): #1号:利用for输出
print(sreadlines[i],end='') print(sreadlines) #读全部内容,并且每一行用'\n'(显示)隔开 #2号:直接输出
f.close() try:
writeFile()
readlinesFile()
except Exception as error:
print(error) 1号结果:
Hello
world
2号结果:
['Hello\n', 'world'] #>>>也就是readlinese()读取数据的储存(list)形式
'''
#读取文件中的学生信息
'''
f = open('student1.txt','rt')
while True: name = f.readline().strip('\n')# *.strip()>>用于移除字符串头尾指定的字符(默认为空格或换行符)或字符序列。
if name == '':
break
gender = f.readline().strip('\n')
age = f.readline().strip('\n')
f.close()
print(name,gender,age)
''' #文件编码
'''
#GBK编码:中文字符包含简体和繁体字符,每个字符仅能存储简体中文字符 汉字占二字节
#*UTF-8编码:全球通用的编码(默认使用)汉字占三字节
#文件打开时,可以指定用encoding参数指定编码例如:
# f = open('x.txt','wt',encoding = 'utf-8')
# 文件编码直接决定了文件的空间大小
'''
#案例:UTF-8文件编码
'''
def writeFile():
f = open('utf.txt','wt',encoding = 'utf-8')
f.write('Hello I am 王宇阳')
f.close() def readFile():
f = open('utf.txt','rt',encoding='utf-8')
sreadlines = f.readlines()
for i in sreadlines:
print(i)
f.close()
try:
writeFile()
readFile()
except Exception as error:
print(error) # 结果: Hello I am 王宇阳
''' #文件指针(文件结束标志:EOF)...文件对象.tell()[返回一个整数,整数则是指针的位置]
'''
f = open('zz.txt','wt',encoding='utf-8')
print(f.tell()) #指针位置:0
f.write('abcdef 你好')
print(f.tell()) #指针位置:13
f.close()
f = open('zz.txt','rt',encoding='utf-8')
f.tell() #文件指针归零
s = f.read(3)
print(s,f.tell()) #输出read读取内容并返回指针位置。读取大小和指针位置相符
f.close()
#结果:
0
13
abc 3
'''
#操作指针...文件对象.seek(offset[,whence])
# offset:开始的偏移量,代表着需要偏移的字节数
# whence:[可选]默认值为‘0’,给offset参数一个定义,表示从那个位置开始偏移,0:文件开头 1:文件当前位置 2:文件末尾
#----注意,只有 “rt+ wt+ at+” 的打开方式可以调整指针,其他的打开方式不支持指针操作
'''
def writeFile():
f = open('zz1.txt','wt+',encoding='utf-8')
print(f.tell()) #返回初始指针位置 >>> 0
f.write('123') #写入3字节内容
print(f.tell()) #返回当前(写入文件后的)指针位置
f.seek(2,0) #指针从开头位置偏移2字节即:1 2 . 3(点的位置)
print(f.tell()) #返回指针位置>>>2
f.write('abc') #从当前指针位置写入‘abc’(覆盖了‘3’)
print(f.tell()) #返回指针位置>>>5
f.close() def readFlie():
f = open('zz1.txt','rt+',encoding='utf-8')
r = f.read()
print(r)
f.close() writeFile()
readFlie()
#结果:
0
3
2
5
12abc
'''
#二进制文件
#打开方式:rb wb ab rb+ wb+ ab+
'''
实践中总结:
1' list内容写入文件在需要专成str格式,应为列表格式文件不接受或者采用 (f.a) 的样式;(案例综合:教材管理95-101行)
'''

python_文件操作代码实例的更多相关文章

  1. python_文件操作

    说明:如有转载,请标明出处!! 一.文件操作 1.文件常用操作方法 open() f=open('文件名','r',encoding='utf-8') #三个参数,第一个文件详细路径,需要写明文件格式 ...

  2. PHP 文件操作代码

    <?php //echo filetype("./1.jpg"); //判断文件类型 文件:file //echo filetype("./code"); ...

  3. 生成TFRecord文件完整代码实例

    import os import json def get_annotation_dict(input_folder_path, word2number_dict): label_dict = {} ...

  4. Redis教程(十五):C语言连接操作代码实例

    转载于:http://www.itxuexiwang.com/a/shujukujishu/redis/2016/0216/143.html 在之前的博客中已经非常详细的介绍了Redis的各种操作命令 ...

  5. java删除文件操作代码备忘

    /** * 删除目录下的所有文件及其自身 * @param file */ private static void deleteFile(File file) { if (file.exists()) ...

  6. Python configparser模块操作代码实例

    1.生成配置文件 ''' 生成配置文件 很多人学习python,不知道从何学起.很多人学习python,掌握了基本语法过后,不知道在哪里寻找案例上手.很多已经做案例的人,却不知道如何去学习更加高深的知 ...

  7. 文件锁及其实例,底层文件I/O操作,基本文件操作和实例,Linux中文件及文件描述符概述

    http://blog.csdn.net/rl529014/article/details/51336161 http://blog.csdn.net/rl529014/article/details ...

  8. PHP文件读写操作之文件写入代码

    在PHP网站开发中,存储数据通常有两种方式,一种以文本文件方式存储,比如txt文件,一种是以数据库方式存储,比如Mysql,相对于数据库存储,文件存储并没有什么优势,但是文件读写操作在基本的PHP开发 ...

  9. JAVA文件操作类和文件夹的操作代码示例

    JAVA文件操作类和文件夹的操作代码实例,包括读取文本文件内容, 新建目录,多级目录创建,新建文件,有编码方式的文件创建, 删除文件,删除文件夹,删除指定文件夹下所有文件, 复制单个文件,复制整个文件 ...

随机推荐

  1. 数据结构_XingYunX(幸运儿)

    数据结构_XingYunX(幸运儿) 问题描述 泡泡最近下了个饱了吗 app,这个 app 推出了个坑蒙拐骗的红包系统,只要花一块钱买张一元抵用券,就有参与 20 元红包的抽奖机会,抽奖界面会实时显示 ...

  2. Visual Studio 2012自动添加注释(如版权信息等)

    http://blog.csdn.net/jiejiaozhufu/article/details/16357721注释宏的原码 /********************************** ...

  3. VMWare虚拟机无法打开内核设备"\\.\Global\vmx86"的解决方法

    cmd执行: 1.net start vmci 2.net start vmx86 3.net start VMnetuserif

  4. .Net Core下基于NPOI对Excel、Word操作封装

    本库进行了重写,如果需要请转移到下文查看: https://www.cnblogs.com/holdengong/p/10889780.html 框架与依赖 框架:.NET Standard 2.0 ...

  5. boostrap selectpicker 用法

    1..html中先引用 <link href="{{ url_for('static', filename='css/bootstrap-select.css') }}" r ...

  6. 编译安装log4cxx

    1.介绍 Log4cxx是开放源代码项目Apache Logging Service的子项目之一,是Java社区著名的log4j的c++移植版,用于为C++程序提供日志功能,以便开发者对目标程序进行调 ...

  7. Xml Helper

    类的完整代码: using System;using System.Collections;using System.Xml; namespace Keleyi.Com.XmlDAL{public c ...

  8. selenium+Node.js在windows下的配置和安装

    转载:http://www.jianshu.com/p/5e64bb70abb8

  9. P2173 [ZJOI2012]网络

    \(\color{#0066ff}{ 题目描述 }\) 有一个无向图G,每个点有个权值,每条边有一个颜色.这个无向图满足以下两个条件: 对于任意节点连出去的边中,相同颜色的边不超过两条. 图中不存在同 ...

  10. sublime中设置view_in_browser

    使用package control 管理的view-in-browser插件,用户可以在浏览器中打开任意当前sublime Text中tab所处的文件,例如html.js等. 1.Ctrl+Shift ...