python对系统文件操作

2017-04-20  本文已影响49人  词穷又词贫

举个例子:
python操作系统文件目录,将网络上下载下来的内容保存到硬盘的文件里。

#!/bin/python3.4
# -*- coding:utf-8 -*-

import os
from requests.exceptions import RequestException
import requests
from hashlib import md5

url = 'http://p3.pstatp.com/origin/1b780001aec9e74e0d9d'
'''图片链接,下载到本地内容的数据是属于二进制数据'''
url1 = 'http://www.baidu.com'
'''页面链接,下载到本地内容的数据是属于文本数据'''

def download_data(url):
    try:
        response = requests.get(url)
        '''根据url,下载数据'''
        if response.status_code == 200:
            print ("正在下载:" + url)
            save_data_local(response.content)
            '''将下载的数据保存至本地,下载的内容也就是图片内容,response.text表示文本内容'''
    except RequestException:
        print ("请求网页数据出错")
        return None

def save_data_local(content):
    path = os.path.join('test')
    if not os.path.exists(path):
        os.mkdir(path)
        '''确认文件存储路径'''
    file_path = "{0}/{1}.{2}".format(path,md5(content).hexdigest(),'jpg')
    '''设置文件存储路径与名字
        {0}:表示路径,可以自定义的路径,os.getcwd() 就表示当前目录下
        {1}:表示文件名字,根据下载内容以其md5值作为文件名
        {2}:表示文件后缀
    格式化一列字符串'''
    if not os.path.exists(file_path):'''同一份内容的md5值相同,避免重复下载'''
        with open(file_path,'wb') as file:
            '''打开文件,wb形式,二进制数据'''
            file.write(content)
            '''将下载的内容写入到打开的文件中'''
            file.close()
            '''关闭文件'''
def main():
    download_data(url)
if __name__ == '__main__':
    main()
    print ("下载完毕")

python之os模块:
# 1、File Names,Command Line,Arguments,and Enviroment Variables
# 2、Process Parameters
# 3、File Object Creation
# 4、File Descriptor Operations
# 5、Files and Directories
# 6、Process Management
# 7、Interface to the scheduler
# 8、Miscellaneous System Information
# 9、Random Numbers

上一篇 下一篇

猜你喜欢

热点阅读