Python對csv檔案讀寫操作

2021-08-19 02:07:48 字數 3288 閱讀 3026

包括使用csv模組進行檔案讀寫,使用requests模組進行檔案傳送。

def pay_task_by_self(self):

global success_writer, fail_writer, cont

dir_path = os.path.dirname(__file__)

file_path = os.path.join(dir_path, 'test.csv')

fail_path = os.path.join(dir_path, 'fail_pay.csv')

success_path = os.path.join(dir_path, 'success_pay.csv')

with open(file_path, 'r') as f:

reader = csv.reader(f)

next(reader)

# 開啟檔案物件

fail_file = open(fail_path, 'w', newline='')

fail_flag = true

success_file = open(success_path, 'w', newline='')

success_flag = true

for row in reader:

# 提取檔案內的資訊

data = dict(mch_no=whale_bank_mch,)

# data['out_merchant_pay_no'] = row[0]

data['out_merchant_pay_no'] = str(uuid.uuid4()).replace('-', '')

data['card_no'] = row[1]

data['coin'] = row[2]

data['amount'] = row[3]

data['merchant_pay_desc'] = row[4]

user = assets.objects.filter(card_no=row[1]).first().user

# 請求支付介面

res = self._request(user=user, url=whale_bank_pay_url, data=data, method=requestresponsemethod.pay)

res['data'] = data

counter = 1

# 代付失敗

if res.get('result_code') != whalebankresultcode.ok:

print('fail-錯誤資訊:' + res['err_msg'])

cont = 'y'

# 支付失敗繼續支付,可設定失敗n次之後選擇是否繼續支付

while res.get('result_code') != whalebankresultcode.ok:

print('卡號:%s的第%s次代付失敗...正在重新支付...' % (data['card_no'], counter))

# 第一次寫入檔案失敗字段

if fail_flag:

fail_header = [k for k in res]

fail_writer = csv.dictwriter(fail_file, fieldnames=fail_header)

fail_writer.writeheader()

fail_flag = false

fail_writer.writerow(res)

# 支付失敗後重新請求

data.pop('sign')

res = self._request(user=user, url=whale_bank_pay_url, data=data, method=requestresponsemethod.pay)

res['data'] = data

time.sleep(1)

counter += 1

# 達到n次失敗後選擇是否繼續支付

if counter == 4:

cont = input('失敗已達%s次,是否繼續?(y/n)' % (counter-1))

if cont == 'y':

pass

else:

break

if cont == 'n':

print('%s取消支付!' % data['card_no'])

else:

print('%s支付成功!' % data['card_no'])

# 代付成功

else:

print('success\n支付成功!')

# 第一次寫入檔案成功字段

if success_flag:

success_header = [k for k in res]

success_writer = csv.dictwriter(success_file, fieldnames=success_header)

success_writer.writeheader()

success_flag = false

success_writer.writerow(res)

time.sleep(0.5)

yield res

# 關閉檔案物件

fail_file.close()

success_file.close()

print('批量代付完成!')

注意:open開啟乙個檔案之後,使用read()方法會讀取出物件中的資訊,再次使用read()讀取會返回空的字串。

執行結果: 

success

支付成功!

>>>>>>>>>>>>>>>>>>>>>>>>>

success

支付成功!

>>>>>>>>>>>>>>>>>>>>>>>>>

success

支付成功!

>>>>>>>>>>>>>>>>>>>>>>>>>

fail-錯誤資訊:使用者卡號錯誤

卡號:1000000000483907的第1次代付失敗...正在重新支付...

卡號:1000000000483907的第2次代付失敗...正在重新支付...

卡號:1000000000483907的第3次代付失敗...正在重新支付...

失敗已達3次,是否繼續?(y/n)n

1000000000483907取消支付!

>>>>>>>>>>>>>>>>>>>>>>>>>

批量代付完成!

Python讀寫csv檔案

1.寫入並生成csv檔案 coding utf 8 import csv csvfile file csv test.csv wb writer csv.writer csvfile writer.writerow 姓名 年齡 data 小河 25 1234567 小芳 18 789456 writ...

python 讀寫csv檔案

1.忽略第一行標題的基礎上 python2.7 coding utf 8 import csv csv reader csv.reader open r c users thinkpad desktop tweets.csv for row in csv reader 條件語句忽略第一行檔案資料 i...

python 讀寫csv檔案

1.將dataframe資料寫入csv 1 用 csv包一行一行的寫入 import csv python2可以用file替代open with open test.csv w as csvfile writer csv.writer csvfile 先寫入columns name writer.w...