我嘗試自動化 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):
按照@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):
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句