Get the App
SLTechnology News&Howtos  ›  Development  › 

How to read and write Files with Python

Shulou Source: shulou.com Published: 2022-06-02 22:14:33 10月18日 Update

This article mainly shows you "Python how to achieve document reading and writing", the content is easy to understand, clear, hope to help you solve your doubts, the following let the editor lead you to study and learn "Python how to achieve document reading and writing" this article.

# python2 str unicode

# python3 bytes str

# python2

S = u 'Hello'

S.encode ('utf8') # format stored in the file

F = open ('hello.txt', 'w')

F.write (s.encode ('utf8'))

F.close ()

F = open ('hello.txt', 'r')

T = f.read (). Decode ('utf8') # Hello

F.close ()

# python3 string is unicode

Strb = biconasdfasdfsdg'

S = 'Hello'

F = open ('hello2.txt',' wt', encoding='utf8') # automatically complete codec

F.write (s)

F.close ()

F = open ('hello2.txt',' rt', encoding='utf8')

S = f.read ()

F.close ()

# deal with binaries, process audio files, turn the volume down and save

F = open ('demo.wav',' rb')

Info = f.read (44) # header

Import struct

Struct.unpack ('hobblemain info [22:24]) # handles file header data operations

Struct.unpack ('iPrependium infi [24:28])

F.seek (0Pol 2)

F.tell ()

N = (f.tell ()-44) / 2

Import array

Buf = array.array ('hags, (0 for _ in xrange (n)

F.seek (44)

F.readinto (buf)

For i in xrange (n): buf [I] / = 8

F2 = open ('demo2.wav',' wb')

F2.write (info)

Buf.tofile (f2)

F2.close ()

# use temporary files

# automatically delete and do not occupy memory

From tempfile import TemporaryFile, NamedTemporaryFile

F = TemporaryFile () # system file system not found

F.write ('abcddee'*100000)

F.seek (0)

F.read (100)

Ntf = NamedTemporaryFile (delete=False) # the file can be found. The file will be deleted after it is turned off by default.

Fname = nft.name

# set file buffering

# I move O operations in blocks, such as 4096 bytes per block

F = open ('test.txt',' walled, buffering=2048) # fully buffered, which will not be written to the file until it is fully buffered

F = open ('test.txt',' wicked, buffering=1) # line buffer,\ nThe file will be written

F = open ('test.txt',' walled, buffering=1) # No buffer, real-time write

F.write ('abc')

# Mapping files to memory

Import mmap

F = open ('demo.bn','r+b')

F.fileno ()

M = mmap.mmap (f.fileno (), 0, access=mmpa.ACCESS_WRITE, offset=mmap.PAGESIZE)

# get a byte array

M [4:8] ='\ xff'*4 # modify the file content directly

# read and write csv data

From urllib import urlretrieve

Urlretrieve ('http://table.finance.yahoo.com/table.csv?s=000001.sz',' pingan.csv')

Rf = open ('pingan.csv',' rb')

Import csv

Reader = csv.reader (rf)

Header = reader.next ()

Wf = open ('pingan_c.csv',' wb')

Writer = csv.writeer (wf)

Writer.writerow (header)

Rf.close ()

Wf.close ()

# read and write json data

Import requests

Import json

From record import Record

Record = Record (channel=1)

AudioData = record.record (2)

From secret import API_KEY, SECRET_KEY

AuthUrl = "https://openapi.baidu.com/oauth/2.0/token?grant_type=client_credentials&client_id=" + API_KEY +" & client_secret= "+

SECRET_KEY

Response = requests.get (authUrl)

Res = json.loads (response.content)

Token = res ['access_token']

# Baidu speech recognition

Cuid = 'xxxxxxxxxxxxx'

SrvUrl = 'http://vop.baidu.com/server_api?cuid=' + cuid +' & token=' + token

HeepHeader = {'Content-Type':' audio/wav; rate = 8000'}

Response = requests.post (srvUrl, headers=httpHeader, data=audioData)

Res = json.loads (response.content)

Text = res ['result'] [0]

Print text

# json.dumps () python objects (lists, dictionaries, etc.) are converted to json strings

# json.dumps (data, sort_keys=True)

# json.loads () json string converted to python object

With open ('demo.json',' wb') as f:

Json.dump (l, f) # writes l data to a file

# Building xml documents

From xml.etree.ElementTree import parse

With open ('demo.xml') with f:

Et = parse (f)

Root = et.getroot ()

Root.tag

Root.attrib

Root.text

# root.getchildren ()

For child in root:

Print child.get ('name')

Root.find ('country')

Root.findall ('country') # direct child element

For e in root.iterfind ('country'):

Print e.get ('name')

From xml.etree.ElementTree import Element, ElementTree, tostring

E = Element ('Data')

E.set ('name',' abc')

E2 = Element ('Row')

E3 = Element ('Open')

E3.text = '8.80'

E2.append (E3)

E.append (e2)

Tostring (e)

Et = ElementTree (e)

Et.write ('demo.xml')

# read and write excel files

Import xlrd, xlwt

Book = xlrd.open_workbook ('demo.xls')

Book.sheets ()

Sheet = book.sheet_by_index (0)

Rows = sheet.nrows

Cols = sheet.ncols

Cell = sheet.cell (0B0) # (0B0) cell

Cell.ctype

Cell.value

Row = sheet.row (1) # cell object list

Data = sheet.row_values (1,1) # column 1 skips the list of values in the first box

Sheet.put_cell (0, cols, xlrd.XL_CELL_TEXT, upright Totalions, None)

Wbook = xlwt.Workbook ()

Wsheet = wbook.add_sheet ('sheet1')

Style = xlwt.easyxf ('align: vertical center, horizontal center')

Wsheet.write (rows,cols, sheet.cell_value (rows,cols), style)

Wsheet.save ('output.xls')

The above is all the contents of the article "how to read and write documents in Python". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Tags: File buffer content data Hello character string object article processing memory byte system learning help binary element unit unit dictionary Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Apple Microsoft NVidia OPPO Reno MySQL