我尝试自动化Django应用程序文件(models.py,views.py,forms.py,template(生产:
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)
并且因为我搜索SO以寻找";CSV";以及";Python";,这是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):