首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

五分钟学会python文件操作

打开或是创建文件

#!/bin/bash/env python

#coding:utf8

context = '''hello world

hello python'''

f = file('hello.txt','w') #打开文件。若文件不存在,则创建文件,打开方式为'w'

f.write(context) #把字符串写入文件

f.colse() #关闭文件

读取文件

#!/bin/bash/env python

#coding:utf8

方法一:使用readline()读文件

f = open('hello.txt')

while True:

line = f.readline()

if line:

print line

else

break

方法二:使用readlines()读文件

f = file('hello.txt')

lines = f.readlines()

for line in lines

print line

f.close()

方法三:使用read()读文件

f = open("hello.txt")

context = f.read()

print context

f.close()

补充:

f.read(5):表示读取5个字符;

f.tell():表示当前文件读取的位置

文件的写入

#!/bin/bash/env python

#coding:utf8

方法一:使用writelines()写文件

f = file('hello.txt','w+') #w+:表示创建并写入

li = ['hello world ','hello python ']

f.writelines(li)

f.close()

方法二:使用write(),a+追加新的内容

f = file('hello.txt','a+') #a+:表示追加

new_text = "goodbye"

f.write(new_text)

f.close()

文件的删除

#!/bin/bash/env python

#coding:utf8

import os

f = file('hello.txt','w')

os.remove("hello.txt")

文件的复制

#!/bin/bash/env python

#coding:utf8

方法一:通过read()和write()实现

src = file('hello.txt','r')

drc = file('hello2.txt','w')

drc.write(src.read())

src.close()

drc.close()

方法二:通过shutil模板实现文件的拷贝

import shutil

shutil.copyfile("hello.txt","hello2.txt") # 将hello.txt复制到hello2.txt

shutil.move("hello.txt","../") #将hello.txt剪切到上一层目录

shutil.move("hello2.txt","hello3.txt") #将hello2.txt重命名为hello3.txt

文件的重命名

#!/bin/bash/env python

#coding:utf8

#修改文件名

import os

li = os.listdir(".") #获取当前目录下的文件列表

print li

if "hello.txt" in li:

os.rename("hello.txt","hi.txt")

elif "hi.txt" in li:

os.rename("hi.txt","hello.txt")

#修改文件的后缀名

import 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)

#修改后缀名2

import os

files = os.listdir(".")

for filename in files:

if li[1] == "html"

newname = li[0] + "htm"

os.rename(filename,newname)

python中对文件、文件夹(文件操作函数)的操作需要涉及到os模块和shutil模块。

os.getcwd()#得到当前工作目录,即当前Python脚本工作的目录路径

os.listdir()#返回指定目录下的所有文件和目录名

os.remove()#函数用来删除一个文件

os.removedirs(r“c:python”)#删除多个目录

os.system()#运行shell命令

os.getenv() 与os.putenv()#读取和设置环境变量

os.rename(old, new)#重命名

os.makedirs(r“c:pythonest”)#创建多级目录

os.mkdir(“test”)#创建单个目录

os.stat(file)#获取文件属性

os.chmod(file)#修改文件权限与时间戳

os.exit()#终止当前进程

内容不完善,剩下的就靠各位自我解决了,哈哈哈哈哈哈哈哈!!

  • 发表于:
  • 原文链接http://kuaibao.qq.com/s/20180127A0D4E900?refer=cp_1026
  • 腾讯「腾讯云开发者社区」是腾讯内容开放平台帐号(企鹅号)传播渠道之一,根据《腾讯内容开放平台服务协议》转载发布内容。
  • 如有侵权,请联系 cloudcommunity@tencent.com 删除。

扫码

添加站长 进交流群

领取专属 10元无门槛券

私享最新 技术干货

扫码加入开发者社群
领券