Python-文件的读写

2022-01-06  本文已影响0人  小小白的jotter

文件的读入

open() 函数

open(name, mode)

name:需要访问文件名称的字符串值

mode:mode决定了打开文件的模式

常用的打开文件的模式

模式 描述
r 以只读方式打开文件。文件的指针将会放在文件的开头。这是默认模式。
w 打开一个文件只用于写入。如果该文件已存在则打开文件,并从开头开始编辑,即原有内容会被删除。如果该文件不存在,创建新文件。
a 打开一个文件用于追加。如果该文件已存在,文件指针将会放在文件的结尾。也就是说,新的内容将会被写入到已有内容之后。如果该文件不存在,创建新文件进行写入。
r+ 打开一个文件用于读写。文件指针将会放在文件的开头。
w+ 打开一个文件用于读写。如果该文件已存在则打开文件,并从开头开始编辑,即原有内容会被删除。如果该文件不存在,创建新文件。
a+ 打开一个文件用于读写。如果该文件已存在,文件指针将会放在文件的结尾。文件打开时会是追加模式。如果该文件不存在,创建新文件用于读写。

读取整个文件

新建一个文件,命名为poem.txt

Who has seen the wind?
Neither I nor you;
But when the leaves hang trembling,
The wind is passing through.

在相同文件夹下创建一个py文件,命名为poem_reader.py

with open('poem.txt') as file_object:
    contents = file_object.read()
    print(contents.rstrip())

关键字with在不再需要访问文件后将其关闭

使用read()到达文件末尾时返回一个空字符从而显示出来一个空行,用rstrip()可以删除字符串末尾的空白

读取文本文件时,Python将其中的所有文本都解读为字符串。

image-20211223141513456

如果需要读取的文件和程序不在同一个文件夹,要写出文件所在路径。

file_path = 'D:\py\poem.txt'
with open(file_path) as file_object:
    contents = file_object.read()
    print(contents.rstrip())
image-20211223142242506

逐行读取

file_path = 'D:\py\poem.txt'
with open(file_path) as file_object:
    for line in file_object:
        print(line.rstrip())
image-20211231153037052

文件内容的使用

file_path = 'D:\py\poem.txt'
with open(file_path) as file_object:
    lines = file_object.readlines()

poem_string = ''

for line in lines:
    poem_string += line.strip()
poem_string1 = poem_string[:22]
print(poem_string1)
print(len(poem_string1))
image-20211231161518424

strip() 方法用于移除字符串头尾指定的字符(默认为空格或换行符)或字符序列,该方法只能删除开头或是结尾的字符,不能删除中间部分的字符

文件的写入

写入空文件

可以创建新的py文件,这里使用之前的poem_reader.py

filename = "poem.txt"
with open(filename,'w') as file_object:
    file_object.write("Who has seen the wind?")

with open(filename, 'r') as file_object:
    contents = file_object.read()
    print(contents)
image-20220106135214863

以写入('w')模式打开文件时,如果指定的文件已经存在,Python将在返回文件对象前清空该文件。

写入多行

filename = "poem.txt"
with open(filename,'w') as file_object:
    file_object.write("Who has seen the wind?\n")
    file_object.write("Neither I nor you;\n")

with open(filename, 'r') as file_object:
    contents = file_object.read()
    print(contents)
image-20220106142238073

附加到文件

打开文件时指定实参'a',将内容附加到文件末尾,而不是覆盖文件原来的内容。

filename = "poem.txt"
with open(filename,'a') as file_object:
    file_object.write("But when the leaves hang trembling,\n")
    file_object.write("The wind is passing through.\n")

with open(filename, 'r') as file_object:
    contents = file_object.read()
    print(contents)
image-20220106144423318
上一篇 下一篇

猜你喜欢

热点阅读