Python新建文件详解:步骤与操作指南
大家好,给大家分享一下如何通过python新建一个文件中的文件,很多人还不知道这一点。下面详细解释一下。现在让我们来看看!
整体文章目录
一、 当前章节目录
二、文件的常见操作
2.1 文件的创建
# 创建文件
context = '''hello world'''
f = open('hello.txt', 'w') # 打开文件
f.write(context) # 把字符串写入文件
f.close() # 关闭文件
运行结果:
2.2 文件的读取
# 使用readline()读文件
f = open("hello.txt")
while True:
line = f.readline()
if line:
print(line)
else:
break
f.close()
运行结果:
hello world
# 使用readlines()读文件
f = open('hello.txt')
lines = f.readline()
for line in lines: # 一次读取多行内容
print(line)
f.close()
运行结果:
# 使用read()读文件
f = open('hello.txt')
context = f.read()
print(context)
f.close()
运行结果:
hello world
f = open("hello.txt")
context = f.read(5) # 读取文件前5个字节内容
print(context)
print(f.tell()) # 返回文件对象当前指针位置
context = f.read(5) # 继续读取5个字节内容
print(context)
print(f.tell()) # 输出文件当前指针位置
f.close()
运行结果:
hello
5
worl
10
2.3 文件的写入
# 使用writelines()写文件
f = open("hello.txt", "w+")
li = ["hello world\n", "hello China\n"]
f.writelines(li)
f.close()
运行结果:
# 追加新的内容到文件
f = open("hello.txt", "a+") # 写入方式为追加a+
new_context = "goodbye"
f.write(new_context)
f.close()
运行结果:
2.4 文件的删除
import os
open("hello.txt", "w")
if os.path.exists("hello.txt"):
os.remove("hello.txt")
2.5 文件的复制
# 使用read()、write()实现复制
# 创建文件hello.txt
src = open("hello.txt", "w")
li = ["hello.txt\n", "hello China\n"]
src.writelines(li)
src.close()
# 把hello.txt复制到hello2.txt
src = open("hello.txt", "r")
dst = open("hello2.txt", "w")
dst.write(src.read())
src.close()
dst.close()
运行结果:
# shutil模块实现文件的复制
import shutil
shutil.copyfile("hello.txt", "hello2.txt")
shutil.move("hello.txt", "../")
shutil.move("hello2.txt", "hello3.txt")
运行结果:
2.6 文件的重命名
# 修改文件名
import glob
import os
li = os.listdir(".")
print(li)
if "hello3.txt" in li:
os.rename("hello3.txt", "hi.txt")
elif "hi.txt" in li:
os.rename("hi.txt", "hello3.txt")
运行结果:
[ ‘7.1.6 文件的重命名.py’, ‘hello3.txt’]
# 修改后缀名
import os # 导入os模块
files = os.listdir(".")
for filename in files:
pos = filename.find(".")
if filename[pos + 1:] == "html":
newname = filename[:pos + 1] + "htm"
os.rename(filename, newname)
运行结果:
import os
files = os.listdir(".")
for filename in files:
li = os.path.splitext(filename)
if li[1] == ".html":
newname = li[0] + ".htm"
os.rename(filename, newname)
运行结果:
import glob
print(glob.glob("*.html"))
运行结果:
[‘test.html’]
2.7 文件内容的搜索和替换
# 文件的查找
import re # 导入re模块
f1 = open("hello.txt", "r")
count = 0
for s in f1.readlines():
li = re.findall("hello", s)
if len(li) > 0:
count = count + li.count("hello")
print("查找到" + str(count) + "个hello")
f1.close()
运行结果:
查找到3个hello
# 文件的替换
f1 = open("hello.txt", "r")
f2 = open("hello2.txt", "w")
for s in f1.readlines():
f2.write(s.replace("hello", "hi"))
f1.close()
f2.close()
运行结果:
2.8 文件的比较
import difflib # 导入difflib模块
f1 = open("hello.txt", "r")
f2 = open("hi.txt", "r")
src = f1.read()
dst = f2.read()
print(src)
print(dst)
s = difflib.SequenceMatcher(lambda x: x == "", src, dst)
for tag, i1, i2, j1, j2 in s.get_opcodes():
print("%s src[%d:%d]=%s dst[%d:%d]=%s" %\
(tag, i1, i2, src[i1:i2], j1, j2, dst[j1:j2]))
运行结果:
2.9 配置文件的访问
# 读配置文件
import configparser # 导入configparser模块
config = configparser.ConfigParser()
config.read("C:\\Users\\86155\\Desktop\\Python\\第7章 使用Python处理文件\\7.1 文件的常见操作\\mysqlconfig.ini")
sections = config.sections() # 返回所有的配置块
print("配置块:", sections)
m = config.options("DATABASE") # 返回所有的配置顶
print("配置项:", m)
d = config.items("DATABASE")
print("内容:", d)
# 根据配置块和配置顶返回内容
host = config.get("DATABASE", "host")
print(host)
user = config.get("DATABASE", "user")
print(user)
passwd = config.get("DATABASE", "passwd")
print(passwd)
port = config.get("DATABASE", "port")
print(port)
database = config.get("DATABASE", "database")
print(database)
运行结果:
配置块: [‘Mysql’, ‘DATABASE’]
配置项: [‘host’, ‘user’, ‘passwd’, ‘port’, ‘database’]
内容: [(‘host’, ‘127.0.0.1’), (‘user’, ‘test’), (‘passwd’, ‘123456’), (‘port’, ‘3306’), (‘database’, ‘jxcia’)]
127.0.0.1
test
123456
3306
jxcia
# 写配置文件
import configparser
config = configparser.ConfigParser()
config.add_section("account") # 添加新的配置块
config.set("account", "username", "user1") # 添加新的配置项
f = open("C:\\Users\\86155\\Desktop\\Python\\第7章 使用Python处理文件\\7.1 文件的常见操作\\mysqlconfig.ini", "a+")
config.write(f)
f.close()
运行结果:
# 修改配置文件
import configparser
config = configparser.ConfigParser()
config.read("C:\\Users\\86155\\Desktop\\Python\\第7章 使用Python处理文件\\7.1 文件的常见操作\\mysqlconfig.ini")
config.set("account", "username", "user2")
f = open("C:\\Users\\86155\\Desktop\\Python\\第7章 使用Python处理文件\\7.1 文件的常见操作\\mysqlconfig.ini", "r+")
config.write(f)
f.close()
运行结果:
# 删除配置文件
import configparser
config = configparser.ConfigParser()
config.read("C:\\Users\\86155\\Desktop\\Python\\第7章 使用Python处理文件\\7.1 文件的常见操作\\mysqlconfig.ini")
config.remove_option("account", "username") # 删除配置顶
config.remove_section("account") # 删除配置块
f = open("C:\\Users\\86155\\Desktop\\Python\\第7章 使用Python处理文件\\7.1 文件的常见操作\\mysqlconfig.ini", "w+")
config.write(f)
f.close()
运行结果:
三、目录的常见操作
3.1 创建和删除目录
import os
os.mkdir("hello")
os.rmdir("hello")
os.makedirs("hello/world")
os.removedirs("hello/world")
3.2 目录的遍历
# 递归遍历目录
import os # 导入os模块
def VisitDir(path):
li = os.listdir(path)
for p in li:
pathname = os.path.join(path, p)
if not os.path.isfile(pathname):
VisitDir(pathname)
else:
print(pathname)
if __name__ == "__main__":
path = r"C:\\Users\\86155\\Desktop\\Python\\第7章 使用Python处理文件\\7.2 目录的常见操作"
VisitDir(path)
运行结果:
C:\Users\86155\Desktop\Python\第7章 使用Python处理文件\7.2 目录的常见操作\7.2.1 创建和删除目录.py
C:\Users\86155\Desktop\Python\第7章 使用Python处理文件\7.2 目录的常见操作\7.2.2 目录的遍历.py
import os
def VisitDir2(path):
for root, dirs, files in os.walk(path):
for filepath in files:
print(os.path.join(root, filepath))
if __name__ == "__main__":
path = r"C:\\Users\\86155\\Desktop\\Python\\第7章 使用Python处理文件\\7.2 目录的常见操作"
VisitDir2(path)
运行结果:
C:\Users\86155\Desktop\Python\第7章 使用Python处理文件\7.2 目录的常见操作\7.2.1 创建和删除目录.py
C:\Users\86155\Desktop\Python\第7章 使用Python处理文件\7.2 目录的常见操作\7.2.2 目录的遍历.py
四、文件处理示例——文件属性浏览程序
import time, os # 导入time,os模块
def showFileProperties(path):
'''显示文件的属性。包括路径、大小、创建日期、最后修改时间,最后访问时间'''
for root, dirs, files in os.walk(path, True):
print("位置:" + root)
for filename in files:
state = os.stat(os.path.join(root, filename))
info = "文件名:" + filename + " "
info = info + "大小:" + ("%d" % state[-4]) + " "
t = time.strftime("%Y-%m-%d %X", time.localtime(state[-1]))
info = info + "创建时间:" + t + " "
t = time.strftime("%Y-%m-%d %X", time.localtime(state[-2]))
info = info + "最后修改时间:" + t + " "
t = time.strftime("%Y-%m-%d %X", time.localtime(state[-3]))
info = info + "最后访问时间:" + t + " "
print(info)
if __name__ == "__main__":
path = r"C:\\Users\\86155\\Desktop\\Python\\第7章 使用Python处理文件"
showFileProperties(path)
运行结果:
D:\anaconda3\python.exe “C:/Users/86155/Desktop/Python/第7章 使用Python处理文件/7.3 文件处理示例——文件属性浏览程序.py”
位置:C:\Users\86155\Desktop\Python\第7章 使用Python处理文件
文件名:7.3 文件处理示例——文件属性浏览程序.py 大小:1063 创建时间:2021-05-14 17:20:48 最后修改时间:2021-05-14 17:38:19 最后访问时间:2021-05-14 17:38:19
文件名:7.5 习题.py 大小:1136 创建时间:2021-05-14 17:43:17 最后修改时间:2021-05-14 18:59:14 最后访问时间:2021-05-14 18:59:14
文件名:hello.txt 大小:24 创建时间:2021-05-13 11:40:27 最后修改时间:2021-06-12 09:40:23 最后访问时间:2021-06-12 09:40:23
文件名:test.txt 大小:62 创建时间:2021-05-14 17:39:18 最后修改时间:2021-05-14 18:48:03 最后访问时间:2021-05-14 18:48:03
文件名:test2.txt 大小:62 创建时间:2021-05-14 18:58:58 最后修改时间:2021-05-14 18:58:58 最后访问时间:2021-05-14 18:58:58
位置:C:\Users\86155\Desktop\Python\第7章 使用Python处理文件\7.1 文件的常见操作
文件名:7.1.1 文件的创建.py 大小:229 创建时间:2021-05-12 11:55:00 最后修改时间:2021-05-12 11:58:16 最后访问时间:2021-05-14 09:04:58
文件名:7.1.2 文件的读取.py 大小:849 创建时间:2021-05-12 11:59:02 最后修改时间:2021-06-11 21:44:12 最后访问时间:2021-06-11 21:44:12
文件名:7.1.3 文件的写入.py 大小:315 创建时间:2021-05-12 19:43:22 最后修改时间:2021-06-11 21:52:11 最后访问时间:2021-06-11 21:52:11
文件名:7.1.4 文件的删除.py 大小:100 创建时间:2021-05-13 11:32:51 最后修改时间:2021-05-13 11:34:40 最后访问时间:2021-05-14 09:04:58
文件名:7.1.5 文件的复制.py 大小:516 创建时间:2021-05-13 11:34:59 最后修改时间:2021-06-12 09:42:30 最后访问时间:2021-06-12 09:42:30
文件名:7.1.6 文件的重命名.py 大小:805 创建时间:2021-05-13 11:46:38 最后修改时间:2021-06-12 10:05:24 最后访问时间:2021-06-12 10:05:24
文件名:7.1.7 文件内容的搜索和替换.py 大小:494 创建时间:2021-05-13 18:39:38 最后修改时间:2021-06-12 10:11:55 最后访问时间:2021-06-12 10:11:55
文件名:7.1.8 文件的比较.py 大小:384 创建时间:2021-05-14 10:19:00 最后修改时间:2021-06-12 10:12:56 最后访问时间:2021-06-12 10:12:56
文件名:7.1.9 配置文件的访问.py 大小:2281 创建时间:2021-05-14 11:50:56 最后修改时间:2021-06-12 11:11:38 最后访问时间:2021-06-12 11:11:38
文件名:hello.txt 大小:30 创建时间:2021-06-12 10:10:08 最后修改时间:2021-06-12 10:11:03 最后访问时间:2021-06-12 10:11:03
文件名:hello2.txt 大小:21 创建时间:2021-06-12 10:11:55 最后修改时间:2021-06-12 10:11:55 最后访问时间:2021-06-12 10:11:55
文件名:hi.txt 大小:24 创建时间:2021-05-13 11:40:27 最后修改时间:2021-06-12 09:43:33 最后访问时间:2021-06-12 09:43:33
文件名:mysqlconfig.ini 大小:149 创建时间:2021-05-14 12:21:48 最后修改时间:2021-06-12 11:11:38 最后访问时间:2021-06-12 11:11:38
文件名:test.html 大小:0 创建时间:2021-05-13 17:55:03 最后修改时间:2021-05-13 17:55:03 最后访问时间:2021-05-13 17:55:03
位置:C:\Users\86155\Desktop\Python\第7章 使用Python处理文件\7.2 目录的常见操作
文件名:7.2.1 创建和删除目录.py 大小:109 创建时间:2021-05-14 17:06:11 最后修改时间:2021-05-14 17:08:04 最后访问时间:2021-05-14 17:08:04
文件名:7.2.2 目录的遍历.py 大小:823 创建时间:2021-05-14 17:09:23 最后修改时间:2021-06-12 11:32:22 最后访问时间:2021-06-12 11:32:22
五、习题
习题:
文件test.txt中包含以下内容:
(1)读取该文件,并输出所有内容用python画小猫。
(2) 去掉文件内容中的换行。
(3)计算出文件的长度。
(4)使用欧冠2020替换2019
(5)创建另一个文件test2.txt,写入本文件的内容。
答案:
# 1) 读取该文件,并输出所有内容。
f = open("test.txt", encoding="utf-8")
context = f.read()
print(context)
f.close()
运行结果:
# 2) 去掉文件内容中的换行。
import re
f1 = open("test.txt", "r+", encoding="utf-8")
context = f1.read()
f1.close()
f1 = open("test.txt", "w+", encoding="utf-8")
for s in context:
f1.write(s.replace("\n", ""))
f1.close()
运行结果:
# 3) 计算出文件的长度。
import re
f2 = open("test.txt", "r+", encoding="utf-8")
context2 = f2.read()
print(len(context))
运行结果:
28
# 4) 使用欧冠2020替换2019
import re
f3 = open("test.txt", "r+", encoding="utf-8")
context3 = f3.readlines()
f3.close()
f3 = open("test.txt", "w+", encoding="utf-8")
for s in context3:
f3.write(s.replace("2019", "欧冠2020"))
f3.close()
运行结果:
# 5) 创建另一个文件test2.txt,写入本文件的内容。
src = open("test.txt", "r", encoding="utf-8")
dst = open("test2.txt", "w", encoding="utf-8")
dst.write(src.read())
src.close()
dst.close()
运行结果:
作者:2301_81895949