python基础:文件操作

 

# 1.打开文件
f = open("a.txt", "a")


# 2.读写操作
# content = f.read()
# print(content)

f.write("1456465")


# 3.关闭文件
f.close()

 

# 1.打开xx.jpg文件,取出内容,获取内容的前半部分
# 1.1打开文件
fromFile = open("xx.jpg", "rb")

# 1.2读取文件内容
fromContent = fromFile.read()
print(fromContent)

# 1.3关闭文件
fromFile.close()



# 2.打开另外一个文件xx2.jpg,然后把取出的半部分内容,写入到xx2.jpg文件中去
# 2.1 打开目标文件
toFile = open("xx2.jpg", "wb")
# 2.2 写入操作
content = fromContent[0: len(fromContent) // 2]
toFile.write(content)


# 2.3 关闭操作
toFile.close()

# 1.打开文件
f = open("a.txt", "r+")


# 2.读写操作
# content = f.read()
# print(content)

f.write("sdsds")


# 3.关闭文件
f.close()

 

f = open("a.txt", "rb")

print(f.tell())
f.seek(-2, 2)
print(f.tell())
print(f.read())
print(f.tell())

f.close()

 

 

# ---------------读

# f = open("a.txt", "r")



# f.read(字节数)
# 	字节数默认是文件内容长度
# 	下标会自动后移
# f.seek(2)
# content = f.read(2)
# print(content)
# print(f.tell())


# f.readline([limit])
# 	读取一行数据
# 	limit
# 		限制的最大字节数
# print("----------", f.tell())
# content = f.readline()
# print(content, end = "")
# print("----------", f.tell())
# content = f.readline()
# print(content, end = '')
# print("----------", f.tell())
# content = f.readline()
# print(content, end = '')
# print("----------", f.tell())


# f.readlines()
# 	会自动的将文件按换行符进行处理
# 	将处理好的每一行组成一个列表返回
# content = f.readlines()
# print(content)
# for i in content:
#     print(i)

# f.close()

# ----------------------遍历
# for in
# 	可以直接遍历 f 本身
# 	也可以遍历行列表

# import collections

f = open("a.txt", "r")

# isinstance(f, collections.Iterator)

# for i in f:
#     print(i, end="")

content = f.readlines()
for i in content:
    print(i, end='')

f.close()


f = open("a.txt", "a")

# isinstance(f, collections.Iterator)

# for i in f:
#     print(i, end="")
if f.readable():
    content = f.readlines()
    for i in content:
        print(i, end='')

f.close()

 

 写入操作

f = open("a.txt", "r")

if f.writable():
    comtent = f.write("abc")
    print(comtent)

f.close()

关闭操作

 文件的相关操作

import os
# os.rename("a.txt", "b.txt")
# os.rename("first", "one")
# os.renames("one/one.txt", "two/two.txt")

# os.remove("xx2.jpg")
# os.rmdir("one")
os.removedirs("one/one2")

 


# os.mkdir("文件夹名称"[, mode])
# 	不能递归创建
os.mkdir("a")

 

# os.mkdir("文件夹名称"[, mode])
# 	不能递归创建
# os.mkdir("a")

# os.chdir("a")
#
# open("cc.txt", "w")

# 获取当前目录
# 	os.getcwd()
# print(os.getcwd())

# 改变默认目录
# 	os.chdir("目标目录")
# 获取目录内容列表
# 	os.listdir("./")

# print(os.listdir("a"))
# print(os.listdir("../"))

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值