美文网首页
python的文件操作

python的文件操作

作者: Dxes | 来源:发表于2019-11-21 00:04 被阅读0次
1.数据的存储
1)数据存储的特点
计算机的内存分为硬盘和运行内存:
硬盘是用来存储文件的,除非手动删除或者硬盘出问题,否则存储在硬盘中的文件一直存在不会销毁;
运行内存是用来存储,程序在运行过程中产生的数据; 当程序运行结束后会自动销毁

如果希望程序中产生的数据在程序运行结束后不销毁,就需要将数据存到硬盘中(需要存在文件中)。

2)常用的文件
txt文件、json文件、plist文件、数据库文件等  -- 文本数据
图片文件(png,jpg等)、音频文件(mp3, wav)、视频文件...   -- 二进制文件
2.文件操作 -操作文件内容
文件操作基本步骤:
打开文件(open) -> 操作文件(读read、写)  -> 关闭文件(close)
"""
# 2.1 打开文件

open(file,mode='r',...,encoding=None) 
open(文件路径, 打开方式, 文本编码方式)  -  以指定的方式打开指定文件并且返回文件对象

说明: 
file  -  文件路径; 可以传文件的绝对路径和相对路径
         1) 绝对路径: 文件在计算机中的全路径
         2) 相对路径: ./   -  表示当前目录(当前写代码的那个文件所在的目录) - 可以省略
                    ../   -  表示当前目录的上层目录
                    .../  -  表示当前目录的上层目录的上层目录

mode  -  文件打开方式, 决定打开文件后的操作权限(能读还是能写 - r/w); 操作的文件的时候数据的类型(文本/二进制 - t/b)
         r - 只读;w - 只写; a - 只写; t - 文本数据(默认,可以不写), b - 二进制数据
         r(rt/tr) - 打开文件后只能进行读操作,读出来的数据是字符串
         rb/br    - 打开文件后只能进行读操作, 读出来的数据是二进制数据(bytes)
         w(wt/tw) - 打开文件后只能进行写操作, 写入的数据是字符串;打开的时候先清空原文件
         wb/bw    - 打开文件后只能进行写操作, 写入的数据是二进制数据;打开的时候先清空原文件
         a(at/ta) - 打开文件后只能进行写操作, 写入的数据是字符串;打开的时候不会清空原文件
         ab/ba    - 打开文件后只能进行写操作, 写入的数据是二进制数据;打开的时候不会清空原文件
         
         注意: a、w在打开文件的时候,如果文件不存在,会自动创建文件
              r在打开文件的时候,如果文件不存在,会报错
              
encoding  -  文本文件编码方式; 只能以t的方式打开文本文件的时候可以赋值
             一般采用'utf-8'的编码方式进行编码;保证同一个文件读和写的编码方式要一致
             
文件路径
# 1)绝对路径
# open(r'/Users/yuting/Workspace/JAVA/授课/python1906/02-语言基础/day13-文件操作和异常捕获/files/test.txt')

# 2)相对路径
# open('./files/test.txt')
# open('files/test.txt')

# 2.==============打开方式=============
# open('files/test.txt', 'a')
# open('files/luffy.jpg', 'wb')

# open('files/a.txt')  # FileNotFoundError: [Errno 2] No such file or directory: 'files/a.txt'
# open('files/a.txt', 'w')
# open('files/b.txt', 'a')
# open('files2/b.txt', 'a')  # FileNotFoundError: [Errno 2] No such file or directory: 'files2/b.txt'

2.2操作文件
"""
1)读操作
文件对象.read()  - 读指定文件,并且返回文件中的内容(所有的文件都支持)
文件对象.readline() - 读指定文件一行的内容(只支持文本文件)

2)写操作
"""
f = open('files/test.txt', 'r', encoding='utf-8')
content = f.read()
print(content)

# 将读写位置移动到文件开头: 文件对象.seek(N)  -  将读写位置移动到第N个字节的位置
f.seek(0)
line = f.readline()
print('line:', line)

# 关闭
f.close()

# print(f.read())   # ValueError: I/O operation on closed file.



# f = open('files/test.txt', 'w')
# content = f.read()  # io.UnsupportedOperation: not readable
# print(content)
print('====================')
f = open('files/test.txt', 'r')
line = f.readline()
print(line)
print('读所有:')
content = f.read()
print(content)

f.close()
# 文本文件打开方式带b,读出来的数据是二进制数据
f = open('files/test.txt', 'rb')
content = f.read()
print(type(content))   # <class 'bytes'>
f.close()

# 注意: 二进制文件(图片、音频、视频、exe文件等)打开的时候必须带b
f = open('files/luffy.jpg', 'rb')
content = f.read()
print(content)

f.close()
# 2.3 写操作
"""
文件对象.write(内容)  - 将指定的内容写入到指定文件中
"""
f = open('files/test.txt', 'a', encoding='utf-8')
f.write('abc')
f.close()

# 如果写的时候带b,写入数据的类型必须是二进制
f = open('files/test.txt', 'ab')
f.write('hello'.encode())
f.close()

num = 100
f = open('files/num.txt', 'w', encoding='utf-8')
f.write(str(num))
f.close()
print('============练习============')
# 练习: 读指定文本文件中的内容,一行一行的读,读完为止
f = open('files/test.txt', 'r', encoding='utf-8')
while True:
    line = f.readline()
    if not line:
        break
    print(line)

f.close()

数据的持久化
"""
1)需要持久化的数据要保存在文件
2)需要数据的时候不是在程序中直接给初始值,而是从本地文件中读数据
3)如果这个数据的值发生改变,要将最新的数据更新到文件中
"""
# 练习: 在程序中用一个变量来记录当前程序启动的次数
# 需要数据的的时候读数据
f = open('files/num.txt', 'r', encoding='utf-8')
count = int(f.read())
print(count)
f.close()

# 数据发生改变后更新文件
count += 1
f = open('files/num.txt', 'w', encoding='utf-8')
f.write(str(count))
f.close()
文件域
"""
打开指定文件,在文件作用域结束后会自动关闭文件
with open(文件路径,打开方式,编码方式) as 文件对象:
    文件作用域
    
"""
with open('files/test.txt', 'r', encoding='utf-8') as f1:
    re = f1.read()
    print(re)

# print(f1.read())   # ValueError: I/O operation on closed file.


# 每次运行程序添加一个学生,要求之前添加的学生要一直存在
"""
张三
[张三]

李四
[张三, 李四]

小明
[张三, 李四, 小明]
"""
with open('files/students.txt', 'r', encoding='utf-8') as f1:
    students = f1.read()

name = input('学生姓名:')
pw = input("输入密码:")
if students == '[]':
    # [张三]
    students = '{}{}{}]'.format(students[:-1], name, pw)
    print(students)
else:
    # [张三,李四]
    students = '{},{},{}]'.format(students[:-1], name, pw)

print(students)

with open('files/students.txt', 'w', encoding='utf-8') as f:
    f.write(students)
3.容器字符串的转换:eval
# eval(字符串) - 将字符串转换成容器型数据类型的数据(要求字符串去掉引号后本身是合法的容器数据)
# 怎么将字符串: '[张三,李四,小明,tom]' 转换成列表: [张三,李四,小明,tom]
str1 = '[1, 2, 3]'
# 将列表字符从转换成列表
re1 = eval(str1)
print(re1, type(re1))
re1.append(100)
print(re1)  # [1, 2, 3, 100]

str2 = "{'a': 10, 'b': 20}"
# 将字典字符串转换成字典
re2 = eval(str2)
print(re2, type(re2))
print(re2['a'])

str3 = "[{'name': '小明', 'age': 18}, {'name': '小花', 'age': 19}, {'name': 'Lisa', 'age': 22}]"
re3 = eval(str3)
print(type(re3))
print(type(re3[0]))

with open('files/student.txt', 'r', encoding='utf-8') as f:
    a = f.read()
print(bool(len(a)))
print(a)

json数据
json模块试试python提供的专门用来支持json数据
# 1.什么是json
"""
json是一种数据格式: 一个json只有一个数据;唯一的这个数据必须是json支持的数据类型的数据

json支持的数据类型:
a.数字类型(number)  -  包含所有的数字(整数和小数), 并且支持科学计数法;数字直接写
                      100  12.5  -3.14  3e4
b.字符串(string)    -  文本数据,只能使用双引号引起来,并且支持转义字符 
                      "abc", "abc123", "hello", "abc\n123", "\u4e00abc"
c.布尔(boolean)    -   只有true和false两个值
d.空值             -   null(表示空)
e.数组(array)      -   [元素1,元素2,元素3,....]  这儿的元素可以json支持的任何类型的数据
f.字典(dictionary) -   {key1:value1, key2:value2, ...} key必须是字符串
"""
2.json转python
json python
数字 int/float
字符串 字符串(单引号)
布尔 布尔(True,False)
null None
数组 列表
字典 字典

方法:

"""
json.loads(字符串)  - 将json格式的字符串转换成python对应的数据
                     注意: 要求这个字符串的内容必须是json格式的数据
"""
result = json.loads('100')
print(result, type(result))

# result = json.loads('abc')   # json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
result = json.loads('"abc"')
print(result, type(result))

result = json.loads('[12, "abc", true, null]')
print(result, type(result))   # [12, 'abc', True, None]  <class 'list'>

b = '{"name": "小明", "age": 100}'
result = json.loads(b)
print(result, result['name'])
3.python转json
python json
int/float 数字
字符串 字符串(双引号)
布尔 布尔(true,false)
None null
列表/元组 数组
字典 字典

方法:

"""
json.dumps(数据)   - 将python数据转换json格式的字符串(返回值是python的字符串,这个字符串的内容是json数据)
"""
result = json.dumps(100)
print([result])   # '100'

result = json.dumps('abc')
print([result])  # '"abc"'

result = json.dumps([True, None, 'hello'])
print([result])   # '[true, null, "hello"]'

result = json.dumps((10, 'abc', False))
print([result])   # '[10, "abc", false]'

a = {10: 100, 'name': 'Tom'}
result = json.dumps(a)
print([result])   # '{"10": 100, "name": "Tom"}'

相关文章

  • 14.Python之文件操作

    Python之文件操作 文件操作通过Python中的内置函数open()对文件进行操作。文件操作需要如下几个参数:...

  • 第二节课:Python 操作文件 ——软件测试派

    学习目标:掌握 python 操作文件 python 提供内置函数 open()实现对文件的操作。 python ...

  • 解析Python中的文件操作

    1.简介 在Python中无需引入额外的模块来进行文件操作,Python拥有内置的文件操作函数(除了内置文件操作函...

  • Python 文件操作

    一. Python 读写 创建文件 Python中对文件,文件夹(文件操作函数)的操作需要涉及到OS 模块和 sh...

  • Python遍历目录并操作文件

    今天来使用python操作文件,包括根据模式查找文件、删除文件操作。 完整代码托管在python/find...

  • python常用文件操作总结

    python 移动文件或文件夹操作。python中对文件、文件夹操作时经常用到的os模块和shutil模块常用方法...

  • python--文件的基本操作

    python编程中,文件是必不可少的。下面我们来学习python中文件的基本操作。 文件的基本操作: 在pytho...

  • 文件操作

    Python基础教程 文件内容操作 python中的文件操作还是挺简单的,类似于php中的文件方法,精简好用。我们...

  • Python

    Python 创建文件 Python 对数据库进行操作--增删改查 Python 对csv进行操作 Python ...

  • Python文件操作

    Python文件操作 准备工作: 1) 使用python来读取文件是非常简单的操作,我们使用open()函数来打开...

网友评论

      本文标题:python的文件操作

      本文链接:https://www.haomeiwen.com/subject/ddtzictx.html