txt文件读写

来源:互联网 发布:年度十大网络流行语 编辑:程序博客网 时间:2024/06/03 11:38
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import random
import string
import winreg
import os




def  readFile(path):
    """
    读取文件全部内容
    path     'c:/intimate.txt'
    """
    with open(path,'r',encoding='utf-8') as f:
        content = f.read()
        print(content)
        return content


def  readFileLines(path):
    """
    读取文件全部内容,把文件每一行作为一个list的一个成员,是一个字符串,并且结尾会有一个换行符"\n",并返回这个list
    path     'c:/intimate.txt'
    """
    with open(path,'r',encoding='utf-8') as f:
        content = f.readlines()
        print(content)
        return content


def  readFileLinesDelkonghang(path):
    """
    读取文件全部内容,把文件每一行作为一个list的一个成员,是一个字符串,并且结尾会没有一个换行符"\n",并且删除空行,并返回这个list
    path     'c:/intimate.txt'
    """
    with open(path,'r',encoding='utf-8') as f:
        lines = f.readlines()
        lines2 =[]
        for line in lines:
             line2=line.strip() #strip() 参数为空时,默认删除空白符(包括'\n', '\r',  '\t',  ' ')
             if len(line2)!=0:
                lines2.append(line2)
        print(lines2)
        return lines2




def get_desktop():
    """
    获取当前系统的桌面的路径
    """
    return os.path.join(os.path.expanduser("~"), 'Desktop')


def random_str(len):
    """
    随机字符串


    ascii中的标点符号 
    print string.ascii_letters
    print string.digits
    print string.punctuation
    输出结果如下:
    abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
    0123456789
    !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
    """
    salt = ''.join(random.sample(string.ascii_letters + string.digits, len))
    return salt


def creat_desktop_file_write(content):
    """
    在桌面路径创建一个文本,写入content ,可以写入list 和词典
    """
    filepath =  get_desktop()+ '/'+random_str(8)+'.txt'
    print(filepath)
    with open(filepath,'a+',encoding='utf-8') as f:
        if type(content) is list:
            for line in content:
                f.write(str(line)+'\n')
                f.flush()
        elif type(content) is dict:
            for k in content:
                f.write(str(k)+'\t\t'+str(content[k])+'\n')
                f.flush()
        else:
            f.write(str(content)+'\n')
            f.flush()




#多线程文件写入,不要文件关闭f.close
def write_to_test(content):
        with open('D:/test.log','a+',encoding='utf-8') as f:
            if type(content) is list:
                for line in content:
                    f.write(str(line)+'\n')
                    f.flush()
            elif type(content) is dict:
                for k in content:
                    f.write(str(k)+'\t\t'+str(content[k])+'\n')
                    f.flush()
            else:
                f.write(str(content)+'\n')
                f.flush()
原创粉丝点击