python 文件操作

2018-01-20  本文已影响9人  sunflower1518
# f=open('/Users/machou/Desktop/pyfils/hello2.txt','r', encoding="gb2312")
#每次读1行
# for line in f.readlines():
#     print(line.strip()) # 把末尾的'\n'删掉
# f.close()

fpath=r'/Users/machou/Desktop/pyfils/hello2.txt'
#追加到文件末尾怎么办?可以传入'a'以追加(append)模式写入。
# with open('/Users/machou/Desktop/pyfils/hello2.txt','a',encoding='utf-8') as f:
#     f.write('-啊-')


#不用考虑报错,不用close()
# with open('/Users/machou/Desktop/pyfils/hello2.txt','r') as f:
#     print(f.read())

# 查看当前目录的绝对路径:
os.path.abspath('.')
print(os.path.abspath('.'))

#拼接路径
newdir= os.path.join(os.path.abspath('.'),'newDir')
print(newdir)
##创建文件夹,若已存在报错
# os.mkdir(newdir)
##删除文件夹
# os.rmdir(newdir)


os.path.split('/Users/michael/testdir/file.txt')
#('/Users/michael/testdir', 'file.txt')
os.path.splitext('/path/to/file.txt')
#('/path/to/file', '.txt')
for line in  os.path.split('/Users/michael/testdir/file.txt/file222.txt'):
   print(line)     #/Users/michael/testdir/file.txt  和  file222.txt

for line in os.path.splitext('/Users/michael/testdir/file.txt/file22.txt'):
   print(line)   #/Users/michael/testdir/file.txt/file22 和 .txt

#当前文件夹新建文件,写入内容,重命名,并删除
currentDir= os.path.join(os.path.abspath('.'),'newfile.txt')
print(currentDir)
f=open(currentDir,'w')   #会覆盖原内容
f.write('test new file')
f.close()
#对文件重命名:
os.rename('newfile.txt','rename-newfile.txt')
os.remove('rename-newfile.txt')
参考:https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/001431925324119bac1bc7979664b4fa9843c0e5fcdcf1e000

# python获取当前目录下及子目录下的所有文件名 http://blog.csdn.net/guoqianqian5812/article/details/52785746
import os
def getListFiles(path):
    ret = []
    for root, dirs, files in os.walk(path):
        for filespath in files:
            ret.append(os.path.join(root,filespath))
    return ret

def getcount(num):
    ret = num*num
    return ret
def file_name(file_dir):
    for root, dirs, files in os.walk(file_dir):
        print('-------------50--------------')
        print(root) #当前目录路径
        print('-------------51--------------')
        print(dirs) #当前路径下所有子目录
        print('-------------52--------------')
        print(files) #当前路径下所有非目录子文件

#定义一个方法,复制一个文件夹下的所有文件,新文件名后+copy
def copyfiles(file_dir):
    for root,dirs,files in os.walk(file_dir):
        for afile in files:
            if afile == '.DS_Store':
                continue
            newfilename=os.path.splitext(afile)[0]+'_copy'+os.path.splitext(afile)[1]
            print(newfilename)
            oldDirfilename = os.path.join(file_dir, afile)
            newDirfileName = os.path.join(file_dir, newfilename)
            with open(oldDirfilename,'r',encoding='utf-8') as f:
                content = f.read()
                # print(f.read())
                with open(newDirfileName,'w',encoding='utf-8') as fson:
                    fson.write(content)
                    fson.close()
                f.close()
                print('-------------文件结束--------------')

if __name__ == '__main__':
    ret = getListFiles(os.path.abspath('.'))
    for each in ret:
        print(each)
    # for each in ret:
    print(getcount(3))
    print('-------------5--------------')
    # file_name(os.path.abspath('.'))
    print('-------------6--------------')
    copyfiles('/Users/machou/Desktop/pyfils')
上一篇下一篇

猜你喜欢

热点阅读