人生苦短_我用Python_OS对目录/文件操作_005

# coding=utf-8

import os  # 操作文件和目录

print("1", os.getcwd())  # 获取当前文件的目录

print("2", os.path.realpath(__file__))

# __file__表示当前你正在编辑的文件

# os.mkdir('test_lemon.txt')   # 新建目录
# os.rmdir('python3.4')  # 删除目录
#
# current_dir = os.getcwd()
# new_dir = os.path.join(current_dir, "python3.4")
# os.mkdir(new_dir)


print(os.listdir())  # 返回的数据是当前文件下所有文件->以列表显示

print(os.path.isfile(__file__))  # 判断当前编辑的文件是否是一个文件,返回布尔值
print(os.path.isdir(__file__))  # 判断当前编辑的文件是否是一个目录,返回布尔值

current_url = os.getcwd()
print("当前文件夹的Path为:  ", current_url)
print(os.path.split(os.getcwd()))  # 返回的是元组类型,tuple,前面是目录,最后一节是文件夹

print(os.path.split(os.path.realpath(__file__))[0])

print(os.path.exists("test.txt"))  # 判断是否存在,return是否为布尔值
 
 
# coding=utf-8

'''
对二进制文件和非二进制文件的读/写/追加/新建操作
'''

file_ = open('test_demo.txt', 'r')  # 内置函数,
# 绝对路径/相对路径
print(file_)
# 同级
# read 只读   write 只写    append 追加

#   非二进制文件 r r+(可读写,追加)  w w+   a a+(追加,追加+读)
#   二进制文件   rb  rb+ wb  wb+ ab  ab+
'''
# 只读的方式打开
file_ = open("test_demo.txt", 'r')
res_1 = file_.read(5)
res_2 = file_.read(4)
print(res_1, res_2)
'''

'''
# r+读写的方式,写的内容会写在文件的最后面
file_ = open("test_demo.txt", 'r+')
file_.write('demo_test')
res_1 = file_.read()
print(res_1)
'''

# w 只写,如果不存在这个file的话,那么会先新建,然后根据你的要求写入内容
# w 只写,如果这个file存在的话,那么写入的时候会覆盖以前的内容
# w+  读写

file_ = open('test_demo.txt', 'w+', encoding='utf-8')
res_1 = file_.read(5)
res_2 = file_.read(4)
file_.write("权杖型_架构师1111")
print(res_1, res_2)

print(file_.tell())  # 获取光标的位置
file_.close()
# seek方法->>>>移动光标位置,(0,0)移动光标到头部位置
# 第一个参数是要移动的字节,第二个参数是相对哪个位置去移动  0头部 1当前位置   2尾巴


# a+  有新建文件的功能
file_test = open('test_ssss.txt', 'a+')
file_test.write('selenium')
print(file_test.read())

# 上下文管理器    with open as
with open('test_111.txt', 'r+') as f:
    f.write('test')
    res_1 = f.read()
    print(res_1)
    f.close()  # 关闭对文件的操作,避免过度占用资源
 

猜你喜欢

转载自www.cnblogs.com/mrchenyushen/p/9108437.html