python操作文件/文件夹

#!/usr/bin/env python 
#!coding:utf-8

#python操作文件/文件夹

import os
import random

#获取文件目录
pwd = os.getcwd()
#print pwd

#判断是否是文件
dest_file = pwd + '/' + 'test_file'
isfile = os.path.isfile(dest_file)
if isfile == True:
	print 'test_file is a file'
else:
	print 'test_file is not a file'


#判断是否是文件夹
des_dir = pwd + '/' + 'testdir'
isdir = os.path.isdir(des_dir)
if isdir == True:
	print 'test_dir is a dir'
else:
	print 'test_dir is not a dir'

#判断文件/文件夹是否存在
destfile = pwd + '/' + 'testdir'
ret = os.path.exists(destfile)
if ret == True:
	print '%s exists' % destfile

#创建目录
#mkdir只能创建一层目录,
if os.path.exists('testdir1') == False:
	os.mkdir('testdir1')

#path = os.path.dirname('testdir1')
#print path

#创建多层目录
if os.path.exists('testdir2/dir/') == False:
	ret = os.makedirs('testdir2/dir/')

#文件的创建,写入,修改,删除

#创建文件
def create_file(filepath):
	f = open(filepath, 'a')	#打开一个文件,不存在则创建;mode:'a', 'w', 'r'
	for i in range(0,9):
		f.write(str(random.randint(0,9)))
		f.write('\n')
	f.close()
	return 0 

#修改文件,先将文件清空,重新写入
def modify_file(filepath):
	f = open(filepath, 'w+')
	f.truncate()
	content = read_file(filepath)
	for i in range(0,9):
		f.write(str(random.randint(0,10)))
		f.write('\n')
	f.close()
	return 0

#读取文件
def read_file(filepath):
	f = open('hello.txt', 'r')
	file_content = ''
	line = f.readline()
	file_content += line
	while line:
		line = f.readline()
		file_content += line
	f.close()
	return file_content 
	#return  file_content

if not os.path.exists('hello.txt'):
	create_file('hello.txt')	
if os.path.exists('hello.txt'):
	print '\n**************hello.txt*************'
	file_content = read_file('hello.txt')
	print file_content
	print '**************hello.txt***************\n'
if os.path.exists('hello.txt'):
	modify_file('hello.txt')
	print '\n*************modify hello.txt*******'
	file_content = read_file('hello.txt')
	print file_content
	print '***************modify hello.txt*******\n'

#删除文件
result = raw_input('确定删除文件hello.txt吗,请输入yes or no:\n')
#文件删除os.remove
if result.upper() == 'YES': #转换为大写,则用户输入的时候就不用区分大小写
	if os.path.exists('hello.txt') == True:
		os.remove('hello.txt')
		print 'del hello.txt'
	else:
		print 'please input yes or no'
if result.upper() != 'YES' and result.upper() != 'NO':
	print 'please input yes or no'


在python解释器中可以用help(file)查看更过有关文件操作的方法


未完,待续。。。。


  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值