Python读写unicode文件的方法(精选6篇)
作者:Sephiroth 字体:[增加 减小] 类型:
#coding=utf-8 import os import codecs def writefile(fn, v_ls): f = codecs.open(fn, ‘wb‘, ‘utf-8‘) for i in v_ls: f.write(i + os.linesep) f.close def readfile(fn): f = codecs.open(fn,‘r‘,‘utf-8‘) ls = [ line.strip() for line in f] f.close() for i in ls: print i if __name__ == ‘__main__‘: fn = u‘11.txt‘ ls = [u‘1.python‘, u‘2.how to pythonic‘, u‘3.python cook‘, u‘python编程‘] writefile(fn, ls) readfile(fn)
希望本文所述对大家的Python程序设计有所帮助,
这篇文章主要介绍了Python实现分割文件及合并文件的方法,涉及Python针对文件的分割与合并操作相关技巧,通过自定义函数split与join实现了文件的分割与合并操作,需要的朋友可以参考下
本文实例讲述了Python实现分割文件及合并文件的方法,分享给大家供大家参考。具体如下:
分割文件split.py如下:
#!/usr/bin/python########################################################################### split a file into a set of parts; join.py puts them back together;# this is a customizable version of the standard unix split command-line # utility; because it is written in Python, it also works on Windows and# can be easily modified; because it exports a function, its logic can # also be imported and reused in other applications;##########################################################################import sys, skilobytes = 1024megabytes = kilobytes * 1000chunksize = int(1.4 * megabytes) # default: roughly a floppydef split(fromfile, todir, chunksize=chunksize): if not os.path.exists(todir): # caller handles errors os.mkdir(todir) # make dir, read/write parts else: for fname in os.listdir(todir): # delete any existing files os.remove(os.path.join(todir, fname)) partnum = 0 input = open(fromfile, ‘rb‘) # use binary mode on Windows while 1: # eof=empty string from read chunk = input.read(chunksize) # get next part <= chunksize if not chunk: break partnum = partnum+1 filename = os.path.join(todir, (‘part%04d‘ % partnum)) fileobj = open(filename, ‘wb‘) fileobj.write(chunk) fileobj.close # or simply open().write() input.close() assert partnum <= 9999 # join sort fails if 5 digits return partnumif __name__ == ‘__main__‘: if len(sys.argv) == 2 and sys.argv[1] == ‘-help‘: print ‘Use: split.py [file-to-split target-dir [chunksize]]‘ else: if len(sys.argv) < 3: interactive = 1 fromfile = raw_input(‘File to be split? ‘) # input if clicked todir = raw_input(‘Directory to store part files? ‘) else: interactive = 0 fromfile, todir = sys.argv[1:3] # args in cmdline if len(sys.argv) == 4: chunksize = int(sys.argv[3]) absfrom, absto = map(os.path.abspath, [fromfile, todir]) print ‘Splitting‘, absfrom, ‘to‘, absto, ‘by‘, chunksize try: parts = split(fromfile, todir, chunksize) except: print ‘Error during split:‘ print sys.exc_info()[0], sys.exc_info()[1] else: print ‘Split finished:‘, parts, ‘parts are in‘, absto if interactive: raw_input(‘Press Enter key‘) # pause if clicked
合并文件join_file.py如下:
#!/usr/bin/python########################################################################### join all part files in a dir created by split.py, to recreate file. # This is roughly like a ‘cat fromdir/* > tofile‘ command on unix, but is # more portable and configurable, and exports the join operation as a # reusable function. Relies on sort order of file names: must be same # length. Could extend split/join to popup Tkinter file selectors.##########################################################################import os, sysreadsize = 1024def join(fromdir, tofile): utput = open(tofile, ‘wb‘) parts = os.listdir(fromdir) parts.sort() for filename in parts: filepath = os.path.join(fromdir, filename) fileobj = open(filepath, ‘rb‘) while 1: filebytes = fileobj.read(readsize) if not filebytes: break output.write(filebytes) fileobj.close() output.close()if __name__ == ‘__main__‘: if len(sys.argv) == 2 and sys.argv[1] == ‘-help‘: print ‘Use: join.py [from-dir-name to-file-name]‘ else: if len(sys.argv) != 3: interactive = 1 fromdir = raw_input(‘Directory containing part files? ‘) tofile = raw_input(‘Name of file to be recreated? ‘) else: interactive = 0 fromdir, tofile = sys.argv[1:] absfrom, absto = map(os.path.abspath, [fromdir, tofile]) print ‘Joining‘, absfrom, ‘to make‘, absto try: join(fromdir, tofile) except: print ‘Error joining files:‘ print sys.exc_info()[0], sys.exc_info()[1] else: print ‘Join complete: see‘, absto if interactive: raw_input(‘Press Enter key‘) # pause if clicked
这篇文章主要介绍了python压缩文件夹内所有文件为zip文件的方法,可实现简单的zip文件压缩功能,需要的朋友可以参考下
本文实例讲述了python压缩文件夹内所有文件为zip文件的方法,分享给大家供大家参考。具体如下:
用这段代码可以用来打包自己的文件夹为zip,我就用这段代码来备份
import zipfilez = zipfile.ZipFile(‘my-archive.zip‘, ‘w‘, zipfile.ZIP_DEFLATED)startdir = “/home/johnf”for dirpath, dirnames, filenames in os.walk(startdir): for filename in filenames: z.write(os.path.join(dirpath, filename))z.close
close()方法方法关闭打开的文件,关闭的文件无法读取或写入更多东西。文件已被关闭之后任何操作会引发ValueError。但是调用close()多次是可以的。
Python自动关闭,当一个文件的引用对象被重新分配给另外一个文件。它使用close()方法来关闭一个文件一个很好的做法。
语法
以下是close()方法的语法:
fileObject.close();
参数
NA
返回值
此方法不返回任何值
例子
下面的例子显示了close()方法的使用
#!/usr/bin/python# Open a filefo = open(“foo.txt”, “wb”)print “Name of the file: ”, fo.name# Close opend filefo.close()
当我们运行上面的程序,它会产生以下结果:
next()方法当一个文件被用作迭代器,典型例子是在一个循环中被使用,next()方法被反复调用,此方法返回下一个输入行,或引发StopIteration异常EOF时被命中。
与其它文件的方法,如ReadLine()相结合next()方法工作不正常。然而,usingseek()将文件重新定位到一个绝对位置将刷新预读缓冲器。
语法
以下是next()方法的语法:
fileObject.next();
参数
NA
返回值
此方法返回下一个输入行,
例子
下面的示例演示next()方法的使用。
#!/usr/bin/python# Open a filefo = open(“foo.txt”, “rw+”)print “Name of the file: ”, fo.name# Assuming file has following 5 lines# This is 1st line# This is 2nd line# This is 3rd line# This is 4th line# This is 5th linefor index in range(5): line = fo.next() print “Line No %d - %s” % (index, line)# Close opend filefo.close()
当我们运行上面的程序,它会产生以下结果:
如果文件已连接(与终端设备相关联)到一个tty(状)的设备,isatty()方法返回True,否则返回False,
语法
以下是isatty()方法的语法:
fileObject.isatty();
参数
NA
返回值
如果该文件被连接(与终端设备相关联)到一个tty(类似终端)设备此方法返回true,否则返回false,
例子
下面的例子显示了isatty()方法的使用。
#!/usr/bin/python# Open a filefo = open(“foo.txt”, “wb”)print “Name of the file: ”, fo.nameret = fo.isatty()print “Return value : ”, ret# Close opend filefo.close()
当我们运行上面的程序,它会产生以下结果:
【Python读写unicode文件的方法】推荐阅读:
python获取一组汉字拼音首字母的方法02-07
Python中的hypot方法使用简介11-19
python是什么语言11-19
python人工智能教学06-21
python选择排序算法实例总结10-06
英语的听说读写能力06-26
读写结合促进读写能力10-24
部编教材的读写结合03-09
高中语文读写的特色教学11-13