我嘗試自動化 Django 應用程式檔案(models.py、views.py、forms.py、模板)的生產:
with open('views.py', 'a ', newline='', encoding="UTF8") as f1:
thewriter = csv.writer(f1,delimiter=' ',quotechar='',escapechar=' ',quoting=csv.QUOTE_NONE)
thewriter.writerow(['from django.shortcuts import render, get_object_or_404, redirect',])
thewriter.writerow(['@method_decorator(login_required, name="dispatch")',])
thewriter.writerow(['class PatientCreate(SuccessMessageMixin, CreateView): ',])
...
但我的問題是,由于escapechar = ' '. 我無法根據需要洗掉此引數quoting=csv.QUOTE_NONE,否則我的所有行都由雙引號分隔。
預期輸出
from django.shortcuts import render, get_object_or_404, redirect
@method_decorator(login_required, name="dispatch")
class PatientCreate(SuccessMessageMixin, CreateView):
當前輸出 (注意雙空格):
from django.shortcuts import render, get_object_or_404, redirect
@method_decorator(login_required, name="dispatch")
class PatientCreate(SuccessMessageMixin, CreateView):
uj5u.com熱心網友回復:
按照@Barmar 所指出的,只寫幾行怎么樣:
lines = [
'from django.shortcuts import render, get_object_or_404, redirect',
'@method_decorator(login_required, name="dispatch")',
'class PatientCreate(SuccessMessageMixin, CreateView): ',
]
lines = [line '\n' for line in lines] # add your own line endings
# UTF-8 is default
with open('views.py', 'a ', newline='') as f:
f.writelines(lines)
而且因為我為“CSV”和“Python”搜索了 SO,這是 CSV-Python 解決方案......
因為您的“行”是單列的,所以您實際上永遠不需要“列分隔符”(這就是 CSV 的全部意義,分解資料的列和行)......
因此,將其設定為尚未包含在資料中的內容。我選擇了換行符,因為它看起來不錯。我在第一行添加了一個額外的列print("foo"),以顯示如果您實際上有多個“代碼列”(?!)會發生什么。
但是,這肯定是錯誤的,我想象一些字符潛入資料/代碼破壞了這一點......因為你不想編碼Python 行,你只想撰寫它們。
享受:
import csv
rows = [
['from django.shortcuts import render, get_object_or_404, redirect', 'print("foo")'],
['@method_decorator(login_required, name="dispatch")'],
['class PatientCreate(SuccessMessageMixin, CreateView): '],
]
with open('views.py', 'w', newline='') as f:
writer = csv.writer(f,
delimiter='\n',
quotechar='',
escapechar='',
quoting=csv.QUOTE_NONE
)
for row in rows:
writer.writerow(row)
得到我:
from django.shortcuts import render, get_object_or_404, redirect
print("foo")
@method_decorator(login_required, name="dispatch")
class PatientCreate(SuccessMessageMixin, CreateView):
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/359282.html
