python (五、檔案操作並發進程以及常用系統模組)

來源:互聯網
上載者:User

標籤:art   int   name   使用   font   表示   字典   共用   cep   

 

主要內容有:

文字檔讀寫

open的參數

f = open(‘test.txt‘, ‘r‘, encoding=‘utf-8‘) # r = read, w = write, a = append, b = binary, +表示檔案不存在就建立

    檔案名稱  方式    編碼方式(有時候需要寫,有時不需要寫)

     (與此檔案在同一個目錄下)

texts = f.read()
print(texts)
f.close() 檔案關閉

 # w+覆蓋檔案重新寫入

f = open(...)
try:
  do sth
except:
  pass
finally:
  if f:
    f.close()

使用with簡化異常處理

with open(‘sample.txt‘, ‘r‘) as f:
  line = f.readline()
  while line:
    print(line.strip())
    line = f.readline()

with open(‘sample.txt‘, ‘r‘) as f:
  for line in f.readlines():
    print(line.strip())

檔案內容讀取

 

自己實現readlines功能

 

texts = [‘New line #1 hello python‘, ‘Line #2 first to learn‘]
with open(‘new_sample.txt‘, ‘w‘) as f:
  for text in texts:
    f.write(text + ‘\n‘) #每寫入一行,自己手寫分行符號
with open(‘new_sample.txt‘, ‘a‘) as f:
  f.write(‘Something new\n‘)

 

 

json與CSV檔案操作

json 的檔案的字串一定要 用雙引號括住

 dump把字典寫入json檔案

json.loads與json.dump都可以複製

 import json

 

 

# 類比dumps的實現
def json_dumps(di): # 回去自己實現帶嵌套的情況
  s = ‘{\n‘
    lines = []
  for k, v in di.items():
    _s = ‘"‘ + k + ‘": ‘
    if t·ype(v) != list:
      _s += ‘"‘ + str(v) + ‘"‘
    else:
      items = [‘"‘ + i + ‘"‘ for i in v]
      _s += ‘[‘ + ‘, ‘.join(items) + ‘]‘
    lines.append(_s)
  s += ‘,\n‘.join(lines)
  s += ‘\n}‘
  return s

config = {‘ip‘: ‘192.168.1.1‘, ‘port‘: [‘9100‘, ‘9101‘, ‘9102‘]}
print(json_dumps(config))

# 類比dumps的實現
def json_dumps(di): # 回去自己實現帶嵌套的情況
  s = ‘{\n‘
  lines = []
  for k, v in di.items():
    _s = ‘"‘ + k + ‘": ‘
    if type(v) != list:
      _s += ‘"‘ + str(v) + ‘"‘
    else:
      items = [‘"‘ + i + ‘"‘ for i in v]
    _s += ‘[‘ + ‘, ‘.join(items) + ‘]‘
    lines.append(_s)
  s += ‘,\n‘.join(lines)
  s += ‘\n}‘
  return s
;

config = {‘ip‘: ‘192.168.1.1‘, ‘port‘: [‘9100‘, ‘9101‘, ‘9102‘]}
print(json_dumps(config))

 

csv檔案的讀取

import csv

 

序列化及應用(不太懂)

import pickle

 

多進程與多線程

Python沒有線程ID這個概念,只好提出了線程名字。

 

# 多進程
from multiprocessing import Process
import os

 

 

# 多線程
import time, threading

 

 

進程池與線程池

在notebook裡運行顯示不出來,放在DOS視窗運行

# 進程池
from multiprocessing import Pool
import os, time, random

 

# 多線程的應用
def top3(data):
  data.sort()
  temp_result[threading.current_thread().name] = data[-3:]

data_set = [[1, 7, 8, 9, 20, 11, 14, 15],
      [19, 21, 23, 24, 45, 12, 45, 56, 31],
      [18, 28, 64, 22, 17, 28]]
temp_result = {} #全域變數
threads = []
for i in range(len(data_set)):
  t = threading.Thread(target=top3, name=str(i), args=(data_set[i], ))
  threads.append(t)
for t in threads:
  t.start()
for t in threads:
  t.join()
result = []
for k, v in temp_result.items():
  result.extend(v)
  result.sort()
print(result[-3:])

 

 

 

資料共用與鎖

 

# 鎖
import threading

lock = threading.Lock() 

 

系統庫

 

 後面的東西比較難理解,多學多練

 

 

 

 

 

 

python (五、檔案操作並發進程以及常用系統模組)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.