Python常用的檔案讀寫操作和字串操作

2022-08-01 08:12:09 字數 3229 閱讀 2335

fileutils.py

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

import os

def readstrfromfile(filepath):

"""從檔案中讀取字串str

param filepath: 檔案路徑

return string : 文字字串

"""with open(filepath, "rb") as f:

string = f.read()

return string

def readlinesfromfile(filepath):

"""從檔案中讀取字串列表list

param filepath: 檔案路徑

return lines : 文字字串列表

"""with open(filepath, "rb") as f:

lines = f.readlines()

return lines

def writestrtofile(filepath, string):

"""將字串寫入檔案中

param filepath: 檔案路徑

param string : 字串str

"""with open(filepath, "wb") as f:

f.write(string)

def dumptofile(filepath, content):

"""將資料型別序列化存入本地檔案

param filepath: 檔案路徑

param content : 待儲存的內容(list, dict, tuple, ...)

"""import pickle

with open(filepath, "wb") as f:

pickle.dump(content, f)

def loadfromfile(filepath):

"""從本地檔案中載入序列化的內容

param filepath: 檔案路徑

return content: 序列化儲存的內容(e.g. list, dict, tuple, ...)

"""import pickle

with open(filepath) as f:

content = pickle.load(f)

return content

zhuanma.py

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

import os

import sys

try:

import pkg_resources

get_module_res = lambda *res: pkg_resources.resource_stream(__name__,os.path.join(*res))

except importerror:

get_module_res = lambda *res: open(os.path.normpath(os.path.join(os.getcwd(), os.path.dirname(__file__), *res)), 'rb')

py2 = sys.version_info[0] == 2

default_encoding = sys.getfilesystemencoding()

if py2:

text_type = unicode

string_types = (str, unicode)

iterkeys = lambda d: d.iterkeys()

itervalues = lambda d: d.itervalues()

iteritems = lambda d: d.iteritems()

else:

text_type = str

string_types = (str,)

xrange = range

iterkeys = lambda d: iter(d.keys())

itervalues = lambda d: iter(d.values())

iteritems = lambda d: iter(d.items())

def strdecode(sentence):

if not isinstance(sentence, text_type):

try:

sentence = sentence.decode('utf-8')

except unicodedecodeerror:

sentence = sentence.decode('gbk', 'ignore')

return sentence

def resolve_filename(f):

try:

return f.name

except attributeerror:

return repr(f)

stringutils.py

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

import zhuanma

def jiema(string):

"""將字串轉為unicode編碼

param string: 待轉碼的字串

return : unicode編碼的字串

"""from zhuanma import strdecode

return strdecode(string)

def filterreturnchar(string):

"""過濾字串中的"\r"字元

:param string:

:return: 過濾了"\r"的字串

"""return string.replace("\r", "")

def encodeutf8(string):

"""將字串轉碼為utf-8編碼

:param string:

:return: utf-8編碼的字串

"""return jiema(string).encode("utf-8")

def filtercchar(string):

"""過濾出字串中的漢字

:param string: 待過濾字串

:return: 漢字字串

"""import re

hanzi = re.compile(u"[\u4e00-\u9fa5]+", re.u)

return "".join(re.findall(hanzi, string))

python 關於檔案讀寫常用操作

st size 5 檔案編碼和檔案編碼錯誤處理 f open test.txt r encoding gbk errors ignore 檔案操作 r 讀 open r w 寫 open w a 追加 open a r r w 可讀可寫,檔案若不存在就報錯 ioerror open r w w r ...

Python 檔案的讀寫操作

python 檔案的讀寫操作 usr bin python filename using file.py poem python f file c poem.txt w open for w riting.it will create new file f.write poem write text...

python 檔案的讀寫操作

python 中不管是對檔案的讀還是對檔案的寫都是按行來進行操作的 對檔案的讀寫的一般流程是 1 利用open 函式來開啟檔案,如果是讀檔案操作的話就將open 時檔案的許可權設定為 r 如果是想要對檔案進行寫操作的話就要使用 w 的寫檔案許可權。這裡需要注意的一點是如果檔案存在就會按照指定的方式開...