这篇文章主要介绍了python中如何创建一个新文件,具有一定借鉴价值,需要的朋友可以参考下。希望大家阅读完这篇文章后大有收获,下面让小编带着大家一起了解一下。
本篇文章给大家谈谈python中如何创建一个新文件,以及如何用python新建一个文件,希望对各位有所帮助,不要忘了收藏本站喔python三国源码。
大家好,给大家分享一下如何通过python新建一个文件中的文件,很多人还不知道这一点快码知识。下面详细解释一下。现在让我们来看看!
整体文章目录
一、 当前章节目录
二、文件的常见操作
2.1 文件的创建
# 创建文件
context = '''hello world'''
f = open('', 'w') # 打开文件
f.write(context) # 把字符串写入文件
f.close() # 关闭文件
运行结果:
2.2 文件的读取
# 使用readline()读文件
f = open("")
while True:
line = f.readline()
if line:
print(line)
else:
break
f.close()
运行结果:
hello world
# 使用readlines()读文件
f = open('')
lines = f.readline()
for line in lines: # 一次读取多行内容
print(line)
f.close()
运行结果:
# 使用read()读文件
f = open('')
context = f.read()
print(context)
f.close()
运行结果:
hello world
f = open("")
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("", "w+")
li = ["hello world\n", "hello China\n"]
f.writelines(li)
f.close()
运行结果:
# 追加新的内容到文件
f = open("", "a+") # 写入方式为追加a+
new_context = "goodbye"
f.write(new_context)
f.close()
运行结果:
2.4 文件的删除
import os
open("", "w")
if .exists(""):
os.remove("")
2.5 文件的复制
# 使用read()、write()实现复制
# 创建文件
src = open("", "w")
li = ["\n", "hello China\n"]
src.writelines(li)
src.close()
# 把复制到
src = open("", "r")
dst = open("", "w")
dst.write(())
src.close()
dst.close()
运行结果:
# shutil模块实现文件的复制
import shutil
shutil.copyfile("", "")
("", "../")
("", "")
运行结果:
2.6 文件的重命名
# 修改文件名
import glob
import os
li = os.listdir(".")
print(li)
if "" in li:
os.rename("", "")
elif "" in li:
os.rename("", "")
运行结果:
[ ‘7.1.6 文件的重命名.py’, ‘’]
# 修改后缀名
import os # 导入os模块
files = os.listdir(".")
for filename in files:
pos = (".")
if filename[pos + 1:] == "html":
newname = filename[:pos + 1] + "htm"
os.rename(filename, newname)
运行结果:
import os
files = os.listdir(".")
for filename in files:
li = .splitext(filename)
if li[1] == ".html":
newname = li[0] + ".htm"
os.rename(filename, newname)
运行结果:
import glob
print(("*.html"))
运行结果:
[‘’]
2.7 文件内容的搜索和替换
# 文件的查找
import re # 导入re模块
f1 = open("", "r")
count = 0
for s in lines():
li = re.findall("hello", s)
if len(li) > 0:
count = count + li.count("hello")
print("查找到" + str(count) + "个hello")
f1.close()
运行结果:
查找到3个hello
# 文件的替换
f1 = open("", "r")
f2 = open("", "w")
for s in lines():
f2.write(s.replace("hello", "hi"))
f1.close()
f2.close()
运行结果:
2.8 文件的比较
import difflib # 导入difflib模块
f1 = open("", "r")
f2 = open("", "r")
src = ()
dst = ()
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()
("C:\\Users\\86155\\Desktop\\Python\\第7章 使用Python处理文件\\7.1 文件的常见操作\\")
sections = config.sections() # 返回所有的配置块
print("配置块:", sections)
m = config.options("DATABASE") # 返回所有的配置顶
print("配置项:", m)
d = config.items("DATABASE")
print("内容:", d)
# 根据配置块和配置顶返回内容
host = ("DATABASE", "host")
print(host)
user = ("DATABASE", "user")
print(user)
passwd = ("DATABASE", "passwd")
print(passwd)
port = ("DATABASE", "port")
print(port)
database = ("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") # 添加新的配置块
("account", "username", "user1") # 添加新的配置项
f = open("C:\\Users\\86155\\Desktop\\Python\\第7章 使用Python处理文件\\7.1 文件的常见操作\\", "a+")
config.write(f)
f.close()
运行结果:
# 修改配置文件
import configparser
config = configparser.ConfigParser()
("C:\\Users\\86155\\Desktop\\Python\\第7章 使用Python处理文件\\7.1 文件的常见操作\\")
("account", "username", "user2")
f = open("C:\\Users\\86155\\Desktop\\Python\\第7章 使用Python处理文件\\7.1 文件的常见操作\\", "r+")
config.write(f)
f.close()
运行结果:
# 删除配置文件
import configparser
config = configparser.ConfigParser()
("C:\\Users\\86155\\Desktop\\Python\\第7章 使用Python处理文件\\7.1 文件的常见操作\\")
config.remove_option("account", "username") # 删除配置顶
config.remove_section("account") # 删除配置块
f = open("C:\\Users\\86155\\Desktop\\Python\\第7章 使用Python处理文件\\7.1 文件的常见操作\\", "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 = (path, p)
if not .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 (path):
for filepath in files:
print((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):
'''显示文件的属性c加加和python哪个值得学。包括路径、大小、创建日期、最后修改时间,最后访问时间'''
for root, dirs, files in (path, True):
print("位置:" + root)
for filename in files:
state = ((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\ “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 文件名: 大小:24 创建时间:2021-05-13 11:40:27 最后修改时间:2021-06-12 09:40:23 最后访问时间:2021-06-12 09:40:23 文件名: 大小:62 创建时间:2021-05-14 17:39:18 最后修改时间:2021-05-14 18:48:03 最后访问时间:2021-05-14 18:48:03 文件名: 大小: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 文件名: 大小:30 创建时间:2021-06-12 10:10:08 最后修改时间:2021-06-12 10:11:03 最后访问时间:2021-06-12 10:11:03 文件名: 大小:21 创建时间:2021-06-12 10:11:55 最后修改时间:2021-06-12 10:11:55 最后访问时间:2021-06-12 10:11:55 文件名: 大小:24 创建时间:2021-05-13 11:40:27 最后修改时间:2021-06-12 09:43:33 最后访问时间:2021-06-12 09:43:33 文件名: 大小:149 创建时间:2021-05-14 12:21:48 最后修改时间:2021-06-12 11:11:38 最后访问时间:2021-06-12 11:11:38 文件名: 大小: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
五、习题
习题:
文件中包含以下内容: (1)读取该文件,并输出所有内容用python画小猫。 (2) 去掉文件内容中的换行。 (3)计算出文件的长度。 (4)使用欧冠2020替换2019 (5)创建另一个文件,写入本文件的内容。
答案:
# 1) 读取该文件,并输出所有内容。
f = open("", encoding="utf-8")
context = f.read()
print(context)
f.close()
运行结果:
# 2) 去掉文件内容中的换行。
import re
f1 = open("", "r+", encoding="utf-8")
context = ()
f1.close()
f1 = open("", "w+", encoding="utf-8")
for s in context:
f1.write(s.replace("\n", ""))
f1.close()
运行结果:
# 3) 计算出文件的长度。
import re
f2 = open("", "r+", encoding="utf-8")
context2 = ()
print(len(context))
运行结果:
28
# 4) 使用欧冠2020替换2019
import re
f3 = open("", "r+", encoding="utf-8")
context3 = f3.readlines()
f3.close()
f3 = open("", "w+", encoding="utf-8")
for s in context3:
f3.write(s.replace("2019", "欧冠2020"))
f3.close()
运行结果:
# 5) 创建另一个文件,写入本文件的内容。
src = open("", "r", encoding="utf-8")
dst = open("", "w", encoding="utf-8")
dst.write(())
src.close()
dst.close()
运行结果: