Python系列11-Python文件操作

一.从文件中读取数据

文本文件可存储的数据量多得难以置信:天气数据、交通数据、社会经济数据、文学作品等。每当需要分析或修改存储在文件中的信息时,读取文件都很有用,对数据分析应用
程序来说尤其如此。例如,你可以编写一个这样的程序:读取一个文本文件的内容,重新设置这些数据的格式并将其写入文件,让浏览器能够显示这些内容。
要使用文本文件中的信息,首先需要将信息读取到内存中。为此,你可以一次性读取文件的全部内容,也可以以每次一行的方式逐步读取。

1.1 读取整个文件

要读取文件,需要一个包含几行文本的文件。
下面首先来创建一个文件,它包含关系型数据库的名称以及排名。

Oracle		1
MySQL		2
SQL Server	3
PostgreSQL	4

代码:
文件路径给一定要是’/’,’'会报错

with open('E:/python/file_test/db.txt') as file_object:
    contents = file_object.read()
    print(contents)

测试记录:

Oracle		1
MySQL		2
SQL Server	3
PostgreSQL	4

1.2 逐行读取

读取文件时,常常需要检查其中的每一行:你可能要在文件中查找特定的信息,或者要以某种方式修改文件中的文本。

要以每次一行的方式检查文件,可对文件对象使用for 循环。

代码:

filename = 'E:/python/file_test/db.txt'

with open(filename) as file_object:
    for line in file_object:
        print(line)

测试记录:

E:\python\learn_python1\venv\Scripts\python.exe E:/python/learn_python1/file_test1.py
Oracle		1

MySQL		2

SQL Server	3

PostgreSQL	4

Process finished with exit code 0

我们打印每一行时,发现空白行更多了
为何会出现这些空白行呢?因为在这个文件中,每行的末尾都有一个看不见的换行符,而print 语句也会加上一个换行符,因此每行末尾都有两个换行符:一个来自文件,另一
个来自print 语句。要消除这些多余的空白行,可在print 语句中使用rstrip().

代码:

filename = 'E:/python/file_test/db.txt'

with open(filename) as file_object:
    for line in file_object:
        print(line.rstrip())

测试记录:

E:\python\learn_python1\venv\Scripts\python.exe E:/python/learn_python1/file_test1.py
Oracle		1
MySQL		2
SQL Server	3
PostgreSQL	4

Process finished with exit code 0

1.3 创建一个包含文件各行内容的列表

使用关键字with 时,open() 返回的文件对象只在with 代码块内可用。如果要在with 代码块外访问文件的内容,可在with 代码块内将文件的各行存储在一个列表中,并在with 代码块外使用该列表:你可以立即处理文件的各个部分,也可推迟到程序后面再处理。

代码:

filename = 'E:/python/file_test/db.txt'

with open(filename) as file_object:
    lines = file_object.readlines()

for line in lines:
    print(line.rstrip())

测试记录:

E:\python\learn_python1\venv\Scripts\python.exe E:/python/learn_python1/file_test1.py
Oracle		1
MySQL		2
SQL Server	3
PostgreSQL	4

Process finished with exit code 0

1.4 使用文件的内容

将文件读取到内存中后,就可以以任何方式使用这些数据了。下面以简单的方式使用圆周率的值。首先,我们将创建一个字符串,它包含文件中存储的所有数字,且没有任何空格。

文件信息:

3.1415926535
  8979323846
  2643383279

代码:

filename = 'E:/python/file_test/pi.txt'

with open(filename) as file_object:
    lines = file_object.readlines()

pi_string = ''
for line in lines:
    line_format = line.rstrip()
    line_format = line_format.lstrip()
    pi_string += line_format

print(pi_string)
print(len(pi_string))

测试记录:

E:\python\learn_python1\venv\Scripts\python.exe E:/python/learn_python1/file_test2.py
3.141592653589793238462643383279
32

Process finished with exit code 0

二. 写入文件

保存数据的最简单的方式之一是将其写入到文件中。通过将输出写入文件,即便关闭包含程序输出的终端窗口,这些输出也依然存在:你可以在程序结束运行后查看这些输出,可与别人分享输出文件,还可编写程序来将这些输出读取到内存中并进行处理。

2.1 写入空文件

要将文本写入文件,你在调用open() 时需要提供另一个实参,告诉Python你要写入打开的文件。为明白其中的工作原理,我们来将一条简单的消息存储到文件中,而不是将其打印到屏幕上。

代码:

filename = 'E:/python/file_test/programming.txt'

with open(filename, 'w') as file_object:
    file_object.write("I love programming.")

测试记录:

C:\>more E:\python\file_test\programming.txt
I love programming.

C:\>

2.2 写入多行

函数write() 不会在你写入的文本末尾添加换行符,因此如果你写入多行时没有指定换行符,文件看起来可能不是你希望的那样.

代码:

filename = 'E:/python/file_test/programming.txt'

with open(filename, 'w') as file_object:
    file_object.write("I love programming.\n")
    file_object.write("I love creating new games.\n")

测试记录:

C:\>more E:\python\file_test\programming.txt
I love programming.
I love creating new games.

C:\>

2.3 附加到文件

如果你要给文件添加内容,而不是覆盖原有的内容,可以附加模式 打开文件。你以附加模式打开文件时,Python不会在返回文件对象前清空文件,而你写入到文件的行都将添加到文件末尾。如果指定的文件不存在,Python将为你创建一个空文件。

代码:

filename = 'E:/python/file_test/programming.txt'

with open(filename, 'a') as file_object:
    file_object.write("I also love finding meaning in large databases.\n")
    file_object.write("I lowe creating apps that can run in a browser.\n")

测试记录:

C:\>more E:\python\file_test\programming.txt
I love programming.
I love creating new games.
I also love finding meaning in large databases.
I lowe creating apps that can run in a browser.

三.存储数据

很多程序都要求用户输入某种信息,如让用户存储游戏首选项或提供要可视化的数据。不管专注的是什么,程序都把用户提供的信息存储在列表和字典等数据结构中。用户关闭程序时,你几乎总是要保存他们提供的信息;一种简单的方式是使用模块json 来存储数据。

模块json让你能够将简单的Python数据结构转储到文件中,并在程序再次运行时加载该文件中的数据。你还可以使用json 在Python程序之间分享数据。更重要的是,JSON数据格式并非Python专用的,这让你能够将以JSON格式存储的数据与使用其他编程语言的人分享。这是一种轻便格式,很有用,也易于学习。

3.1 使用json.dump() 和json.load()

我们来编写一个存储一组数字的简短程序,再编写一个将这些数字读取到内存中的程序。第一个程序将使用json.dump() 来存储这组数字,而第二个程序将使用json.load() 。

函数json.dump() 接受两个实参:要存储的数据以及可用于存储数据的文件对象。下面演示了如何使用json.dump() 来存储数字列.

代码:

import json

numbers = [2 ,3 ,5 ,7 ,11 ,13]

filename = 'E:/python/file_test/numbers.json'
with open(filename, 'w') as f_obj:
    json.dump(numbers, f_obj)

测试记录:

C:\>more E:\python\file_test\numbers.json
[2, 3, 5, 7, 11, 13]

C:\>

下面演示了如何使用json.load() 来读取数字列.
代码:

import json

filename = 'E:/python/file_test/numbers.json'
with open(filename) as f_obj:
    numbers = json.load(f_obj)

print(numbers)

测试记录:

E:\python\learn_python1\venv\Scripts\python.exe E:/python/learn_python1/venv/json_test1.py
[2, 3, 5, 7, 11, 13]

Process finished with exit code 0

3.2 保存和读取用户生成的数据

对于用户生成的数据,使用json 保存它们大有裨益,因为如果不以某种方式进行存储,等程序停止运行时用户的信息将丢失。下面来看一个这样的例子:用户首次运行程序时被提示输入自己的名字,这样再次运行程序时就记住他了。

我们先来存储用户的名字.

代码:

import json
#  如果以前存储了用户名,就加载它
#  否则,就用提示用户输入用户名并存储它

filename = 'E:/python/file_test/username.json'

try:
    with open(filename) as f_obj:
        username = json.load(f_obj)
except FileNotFoundError:
    username = input("What is your name?")
    with open(filename, 'w') as f_obj:
        json.dump(username, f_obj)
        print("We'll remember you when you come back, " + username + "!")
else:
    print("Welcome back, " + username + "!")

测试记录:

-- 第一次
E:\python\learn_python1\venv\Scripts\python.exe E:/python/learn_python1/json_test2.py
What is your name? Oracle
We'll remember you when you come back,  Oracle!

Process finished with exit code 0

-- 第二次
E:\python\learn_python1\venv\Scripts\python.exe E:/python/learn_python1/json_test2.py
Welcome back,  Oracle!

Process finished with exit code 0

3.3 重构

你经常会遇到这样的情况:代码能够正确地运行,但可做进一步的改进——将代码划分为一系列完成具体工作的函数。这样的过程被称为重构 。重构让代码更清晰、更易于理解、更容易扩展。

要重构json_test2.py,可将其大部分逻辑放到一个或多个函数中。json_test2.py的重点是问候用户,因此我们将其所有代码都放到一个名为greet_user() 的函数中,获取存量的用户名放在一个名为get_stored_username()的函数中,获取新的输入用户名的信息放在一个名为get_new_username()的函数中。

这样每个函数只做一件事情,greet_user() 没有过多的代码,直接调用其余的几个函数即可。

代码:

import json

def get_stored_username():
    """如果存储了用户名,就获取它"""
    filename = 'E:/python/file_test/username.json'
    try:
        with open(filename) as f_obj:
            username = json.load(f_obj)
    except FileNotFoundError:
        return None
    else:
        return username

def get_new_username():
    """提示用户输入用户"""
    username = input("What is your name?")
    filename = 'E:/python/file_test/username.json'
    with open(filename, 'w') as f_obj:
        json.dump(usernmae, f_obj)
    return username

def greet_user():
    """问候用户,并指出其名字"""
    username = get_stored_username()
    if username:
        print("Welcome back, " + username + "!")
    else:
        username = get_new_username()
        print("We'll remeber you when you come back, " + username + "!")

greet_user()

测试记录:

E:\python\learn_python1\venv\Scripts\python.exe E:/python/learn_python1/json_test2.py
Welcome back,  Oracle!

Process finished with exit code 0

参考:

1.Python编程:从入门到实践

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值