文件

1.打开文件

with open("E:\\nihao.txt") as f: #with 这个关键字不需要访问文件之后将他关闭,
    contents=f.read()
    print(contents.rstrip())
path=r"E:\nihao.txt" #直接读入路径,或者给路径命名读入也可以
f=open(path)
m=f.read()
print(m)
path=r"C:\Users\zhangfayu\Desktop\nihao.txt" # ##注意windows中 应该以原始字符串的方式指定路径,即在开头的单引号前面加上r
f=open(path) 
m=f.readline()
print(m.rstrip())

以上,读入整个文件,且不分行

filename=r"C:\Users\zhangfayu\Desktop\nihao.txt"
with open(filename) as file_object:
    for line in file_object: #按行读入
        print(line)
 filename=r"C:\Users\zhangfayu\Desktop\nihao.txt"
with open(filename) as file_object:
    lines=file_object.readlines()#readlines 函数,从文件中读取每一行,并将它们存储在一个列表中
for line in lines:
        print(line)
#使用文件的内容
filename="pi_digists.txt"
with open(filename) as file_object:
    lines=file_object.readlines()
pi_string=""
for line in lines:
    pi_string+=line.strip()
print(pi_string[:10])
print(len(pi_string))
#查看某些数在不在圆周率里面
filename="pi_digists.txt"
with open(filename) as file_object:
    lines=file_object.readlines()
pi_string=""
for line in lines:
    pi_string+=line.strip()
birthday=input("please input you birthady:")
if birthday in pi_string:
    print("yes")
else:
    print("no")

2.写入文件

#写入文件 open()函数有两个参数,第一个是文件名称或者路径,第二个是打方式,‘r’默认只读打开,‘w’以写打开,但是会覆盖原本文件内容
                                 #‘a’以写入打开,在文件末尾写入,‘b’以二进制模式打开文件
filename="pi_digists.txt"
with open(filename,'w') as file_object:
    file_object.write("i love you.\n") # ‘w’会覆盖之前的文件已有内容,‘a’是写在文件末尾,加入“\n”可以多行写入
    file_object.write("i love you.\n")
    file_object.write("i love you.\n")
with open(filename,'a') as file_object:
    file_object.write("I love you.\n") # ‘w’会覆盖之前的文件已有内容,‘a’是写在文件末尾,加入“\n”可以多行写入
    file_object.write("I love you.\n")
    file_object.write("I love you.\n")

i love you.
i love you.
i love you.
I love you
I love you
I love you

3.其他操作
python的内置os模块 可以调用操作系统提供的接口函数

#导入模块os
import os
os.getcwd()#获取当前工作目录
os.chdir("E:\\")#切换工作目录
os.getcwd()
os.listdir() #列举出当前目录的文件
os.mkdir('bbb')#创建文件夹
os.makedirs(r"\a\b\c")#创建多层目录
os.system("calc")#打开计算机
imprt os
os.name #操作系统的名称
os.uname # 获取详细的操作系统信息,windows不支持。
 os.environ   #在操作系统中定义的环境变量,全部保存在os.environ这个dict中,可以直接查看
  os.getenv('PATH')   #要获取某个环境变量的值,可以调用os.getenv()函数
  os.path.abspath('.')#绝对路径
  os.path.join('/Users/michael', 'testdir')
  os.mkdir('/Users/michael/testdir')#创建目录
  os.rmdir('/Users/michael/testdir')#删除目录
 os.rename('test.txt', 'test.py')   # 对文件重命名:将txt文件重命名为py文件
  os.remove('test.py')# 删掉文件:
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值