Python编码/文件读取/多线程

个人笔记~~记录才有成长   编码/文件读取/多线程

编码

  常用的一般是gbk、utf-8,而在python中字符串一般是用Unicode来操作,这样才能按照单个字来处理,所以需要对不同的编码格式进行转化。

  这里需要的函数decode和encode,形式都很简单,只要牢记对应的格式对应的编码就好

如果是utf-8,想转换成unicode
content.decode('utf-8')
如果是Utf-8,想转换成gbk
content.decode('utf-8').encode('gbk')

  注意:对于Python可以在.py中指定编码格式,如下选择的是utf-8格式

# -*- coding: utf-8 -*-

文件读取

传统的读法,全部读出,按行处理:

fp=open("./output.txt", "r");
alllines=fp.readlines();
fp.close();
for eachline in alllines:
print eachline;

使用文件迭代器 , 每次只读取和显示一行:

fp=open("./output.txt", "r");
for eachline in fp:
print eachline;

读取和保存CSV文件,使用CSV模块

import csv

def loadFile(file_name):
f = open(file_name)
r = csv.reader(f)
for item in r:
print item
type = sys.getfilesystemencoding()
for line in r: def saveFile(result):
writer = csv.writer(open('result.csv','w'), dialect='excel')
for item in result:
writer.writerow(item)

多线程

  由于程序数据有点大,尝试一下Python的多线程,其实和C++/JAVA都是类似的

调用thread模块中的start_new_thread()函数来产生新线

import time
import thread def timer(n, ID):
cnt = 0
while cnt<n:
print 'Thread:(%d) Time:%s\n'%(ID,time.ctime())
cnt+=1
thread.exit_thread() def test(): #Use thread.start_new_thread() to create 2 new threads
thread.start_new_thread(timer, (5,1))
thread.start_new_thread(timer, (5,2)) if __name__=='__main__':
test()

  python中的线程是通过thread模块来调用的,调用thread.start_new_thread()函数,该函数由两部分参数,第一个参数为线程函数,第二个参数为提供给线程函数的tuple型参数。

使用threading模块的 Thread类

  这里要接触到继承的概念了,这种处理方式相对来说要清晰的多。

  通过调用threading模块继承threading.Thread类来包装一个线程对象。

  • 在自己的线程类的__init__里调用threading.Thread.__init__(self, name = threadname)
  • Threadname为线程的名字
  • run(),通常需要重写,编写代码实现做需要的功能。
  • getName(),获得线程对象名称
  • setName(),设置线程对象名称
  • start(),启动线程
  • jion([timeout]),等待另一线程结束后再运行。
  • setDaemon(bool),设置子线程是否随主线程一起结束,必须在start()之前调用。默认为False。
  • isDaemon(),判断线程是否随主线程一起结束。
  • isAlive(),检查线程是否在运行中。
import time
import thread
import threading def timer1(n, ID):
cnt = 0
while cnt<n:
print 'Thread:(%d) Time:%s\n'%(ID,time.ctime())
cnt+=1
thread.exit_thread() class timer2(threading.Thread): #The timer class is derived from the class threading.Thread
def __init__(self, ID):
threading.Thread.__init__(self)
self.m_ID = ID
self.m_stop = False def run(self):
while not self.m_stop:
time.sleep(2)
print 'Thread Object(%d), Time:%s\n' %(self.m_ID, time.ctime()) def stop(self):
self.m_stop = True def test(): #Use thread.start_new_thread() to create 2 new threads
#thread.start_new_thread(timer1, (5,1))
#thread.start_new_thread(timer1, (5,2))
thread1 = timer2(1)
thread2 = timer2(2)
thread1.start()
thread2.start()
time.sleep(5)
thread1.stop()
thread2.stop() if __name__=='__main__':
test()


本作品采用知识共享署名-非商业性使用-相同方式共享 3.0 未本地化版本许可协议进行许可。欢迎转载,请注明出处:
转载自:cococo点点 http://www.cnblogs.com/coder2012

Python编码/文件读取/多线程的更多相关文章

  1. python大文件读取

    python大文件读取 https://stackoverflow.com/questions/8009882/how-to-read-a-large-file-line-by-line-in-pyt ...

  2. python .dcm文件读取,并转化为.jpg格式

    .dcm文件是DICOM(Digital Imaging and Communications in Medicine)即医学数字成像和通信中记录医学图像和相关信息的文件,在用于医学图像处理的时候我们 ...

  3. Python txt文件读取写入字典的方法(json、eval)

    link:https://blog.csdn.net/li532331251/article/details/78203438 一.使用json转换方法 1.字典写入txt import json d ...

  4. python tips:文件读取——换行符的问题

    问题:在windows系统中,换行的符号是'\r\n'.python在读文件的时候为了系统兼容,会默认把'\r','n','\r\n'都视作换行.但是在windows文件中,可能在同一行中同时存在'\ ...

  5. python应用文件读取写登录注册

    #!/usr/bin/python3# -*- coding: utf-8 -*-# Author: zhw#读取文件中的内容def open_file(filename ,file_type , * ...

  6. 用python实现文件读取和内容替换

    infile = open("D:/test.txt", "r") #打开文件 outfile = open("D:/pp2.txt", & ...

  7. python 编码文件json.loads json.dumps

    import yaml d = {'name': '张三', 'age': '1'} print d jd = json.dumps(d, ensure_ascii=False, encoding=' ...

  8. 中文系统下,UTF-8编码文本文件读取导致的错误

    一.UTF-8编码文件读取导致的错误 有个txt文件,里面内容为: aaa bbb ccc 以UTF-8编码方式打开txt文件,顺序读取,将里面的值放到一个hashset中,并判断aaa是否在在has ...

  9. python编码总结

    关于ASCII码和Unicode码的来源 计算机只能处理数字,如果要处理文本,需要先将文本转换成数字.早期计算机采用8bit作为一个字节(byte).所以一个字节最大为255(二进制11111111= ...

随机推荐

  1. S5PV210的LCD控制器详解

    1.FIMD结构框图 (1)Samsung的s5pv210的LCD控制器叫做FIMD(也叫显示控制器).Display controller(显示控制器)包括用于将图像数据从相机接口控制器的本 地总线 ...

  2. 将Word发布到CSDN

    将Word发布到CSDN 注:以Word2010为例 注册CSDN账号 打开Word新建一篇博客 打开"管理账户"新建一个账户,博客类别选择"其他" API选择 ...

  3. 上传文件时$_FILES为空的解决方法

    上传视频的时候打印$_FILES为空,小的文件就没问题,后来发现是因为传的文件太大, 出现这个问题的原因主要有两个:表单原因或者php设置原因: 1,表单类型: 上传文件的表单编码类型必须设置成 en ...

  4. vi 文字处理器

    vi 的使用 基本上 vi 共分为三种模式,分别是『一般模式』. 『编辑模式』与『指令列命令模式』三种! 这三种模式的作用是: 一般模式: 以 vi 处理一个档案的时后,一进入该档案就是一般模式了.在 ...

  5. openstackM版本常见问题汇总

    汇总下常见的问题以及解释下一些比较容易让人萌的参数配置等等 问题汇总1.使用纯文本模式进行复制粘贴,打死不要用word!!!可以解决绝大多数问题,如果你依然执迷不悟,那么就好自为之吧 2.创建路由器时 ...

  6. 案例:TableLayout表格布局——迷你计算器

    计算器可以常用线性布局(LinearLayout)和表格布局(tableLayout).Gridlayout 今天我用的是表格布局 效果如下: 代码如下: <TableLayout xmlns: ...

  7. PHP的OB缓存(输出缓存)

    使用PHP自带的缓存机制 原则:如果ob缓存打开,则echo的数据首先放在ob缓存.如果是header信息,直接放在程序缓存.当页面执行到最后,会把ob缓存的数据放到程序缓存,然后依次返回给浏览器. ...

  8. ByteArrayInputStream和ByteArrayOutputStream

    public class ByteArrayTest { public static void main(String[] args) throws IOException { read(write( ...

  9. ADB理解

    在做手机测试时候,经常用到的命令就是adb.如adb shell,adb devices,adb logcat等等 那么什么是adb,怎么用呢? 一.adb adb的全称为Android Debug ...

  10. 选择合适的String拼接方法(这篇博客是我抄的)

    package com.test; public class FreeFile { public static void main(String[] args) { // 加号拼接 String st ...