Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在两个csv文件django之间复制内容_Python_Django_Csv - Fatal编程技术网

Python 在两个csv文件django之间复制内容

Python 在两个csv文件django之间复制内容,python,django,csv,Python,Django,Csv,我试图将csvfile的内容复制到csvfile2中。在这个问题上我看不到任何帮助。我还想在csvfile2的第一行附加一个值value。例如:value=1 输出应该是 `1_dog 1_cat 1_frog ` 当value=2时结果应为 2_dog 2_cat 2_frog 该值介于1和csv文件中的行总数之间。(totalrows) 我的试用代码: def csvupload(request, template_name='upload_csv.html'): if request

我试图将
csvfile
的内容复制到
csvfile2
中。在这个问题上我看不到任何帮助。我还想在
csvfile2
的第一行附加一个值
value
。例如:
value=1
输出应该是

`1_dog 1_cat 1_frog `
value=2时
结果应为

2_dog 2_cat 2_frog
该值介于1和csv文件中的行总数之间。(
totalrows

我的试用代码:

def csvupload(request, template_name='upload_csv.html'):

if request.method == 'POST':
    form = CSVUploadForm(request.POST, request.FILES)
    if form.is_valid():
        error_list = set()
        value = 1
        csvfile = request.FILES['file']
        file_name = csvfile.name
        file_name = unicodedata.normalize('NFKD', file_name).encode('ascii','ignore')
        csvfile2 = settings.MEDIA_ROOT + '/new/sample.csv'
        writer = csv.writer(outfile, dialect='excel')
        csvfile.open()
        line_entries = csv.DictReader(csvfile, dialect='excel')
        try:
            csvfile.read()
            line_entries = csv.DictReader(csvfile, dialect='excel', delimiter=',')
            rows1 = list(csvfile)
            totalrows = len(rows1)
            success = True
        except:
            messages.error(request, "Could not parse file, invalid format")
            success = False
            return redirect('home')


        if success:
            messages.success(request, "File read..")
        else:
            for err in error_list:
                messages.error(request, err)
    else:
        messages.error(request, "No file selected")
else:
    form = CSVUploadForm()
context = {
    'form': form
}
return render_to_response(template_name, context, context_instance=RequestContext(request))

这段代码不完整。我是python新手,很困惑。有人能帮忙吗?

我手边没有python解释器,所以无法测试。稍后我可以提供更完整的答案

你需要这样的东西-

阅读-

>>> import csv
>>> with open('names.csv') as csvfile:
...     reader = csv.DictReader(csvfile)
...     for row in reader:
...         print(row['first_name'], row['last_name'])
写—

import csv

with open('names.csv', 'w') as csvfile:
    fieldnames = ['first_name', 'last_name']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)

    writer.writeheader()
    writer.writerow({'first_name': 'Baked', 'last_name': 'Beans'})
    writer.writerow({'first_name': 'Lovely', 'last_name': 'Spam'})
    writer.writerow({'first_name': 'Wonderful', 'last_name': 'Spam'})
因此,首先,将文件保存在服务器中的临时位置-

def handle_uploaded_file(f): # method to save to a temporary location
    with open('some/file/name.csv', 'wb+') as destination:
        for chunk in f.chunks():
            destination.write(chunk)
然后加载它,并按照文档中所述逐行读取

因此,您的代码可能类似于-

def csvupload(request, template_name='upload_csv.html'):

if request.method == 'POST':
    form = CSVUploadForm(request.POST, request.FILES)
    if form.is_valid():
        error_list = set()
        value = 1
        handle_uploaded_file(request.FILES['file']) # save the file

        file_name = csvfile.name
        file_name = unicodedata.normalize('NFKD', file_name).encode('ascii','ignore')
        csvfile2 = settings.MEDIA_ROOT + '/new/sample.csv'
        writer = csv.writer(outfile)
        row_number = 0
        try:
            with open(csvfile2, 'w') as writtenFile:
                fieldnames = ... # use some code to determine the column names dynamically, may be read the first row and then populate the field names
                writer = csv.DictWriter(writtenFile, fieldnames=fieldnames)
                    writer.writerow({...})  # write header row
                with open('some/file/name.csv') as csvfile:
                    line_entries = csv.DictReader(csvfile)
                    for row in line_entries:
                        row_number = row_number + 1
                        valueDict = [...] # populate the rows as a dict
                        writer.writerow(valueDict);
            success = True
        except:
            messages.error(request, "Could load file, invalid format")
            success = False
            return redirect('home')


        if success:
            messages.success(request, "File read..")
        else:
            for err in error_list:
                messages.error(request, err)
    else:
        messages.error(request, "No file selected")
else:
    form = CSVUploadForm()
context = {
    'form': form
}
return render_to_response(template_name, context, context_instance=RequestContext(request))

我手头没有python解释器,因此无法进行测试。稍后我可以提供更完整的答案

你需要这样的东西-

阅读-

>>> import csv
>>> with open('names.csv') as csvfile:
...     reader = csv.DictReader(csvfile)
...     for row in reader:
...         print(row['first_name'], row['last_name'])
写—

import csv

with open('names.csv', 'w') as csvfile:
    fieldnames = ['first_name', 'last_name']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)

    writer.writeheader()
    writer.writerow({'first_name': 'Baked', 'last_name': 'Beans'})
    writer.writerow({'first_name': 'Lovely', 'last_name': 'Spam'})
    writer.writerow({'first_name': 'Wonderful', 'last_name': 'Spam'})
因此,首先,将文件保存在服务器中的临时位置-

def handle_uploaded_file(f): # method to save to a temporary location
    with open('some/file/name.csv', 'wb+') as destination:
        for chunk in f.chunks():
            destination.write(chunk)
然后加载它,并按照文档中所述逐行读取

因此,您的代码可能类似于-

def csvupload(request, template_name='upload_csv.html'):

if request.method == 'POST':
    form = CSVUploadForm(request.POST, request.FILES)
    if form.is_valid():
        error_list = set()
        value = 1
        handle_uploaded_file(request.FILES['file']) # save the file

        file_name = csvfile.name
        file_name = unicodedata.normalize('NFKD', file_name).encode('ascii','ignore')
        csvfile2 = settings.MEDIA_ROOT + '/new/sample.csv'
        writer = csv.writer(outfile)
        row_number = 0
        try:
            with open(csvfile2, 'w') as writtenFile:
                fieldnames = ... # use some code to determine the column names dynamically, may be read the first row and then populate the field names
                writer = csv.DictWriter(writtenFile, fieldnames=fieldnames)
                    writer.writerow({...})  # write header row
                with open('some/file/name.csv') as csvfile:
                    line_entries = csv.DictReader(csvfile)
                    for row in line_entries:
                        row_number = row_number + 1
                        valueDict = [...] # populate the rows as a dict
                        writer.writerow(valueDict);
            success = True
        except:
            messages.error(request, "Could load file, invalid format")
            success = False
            return redirect('home')


        if success:
            messages.success(request, "File read..")
        else:
            for err in error_list:
                messages.error(request, err)
    else:
        messages.error(request, "No file selected")
else:
    form = CSVUploadForm()
context = {
    'form': form
}
return render_to_response(template_name, context, context_instance=RequestContext(request))

1_狗1_猫1_蛙
似乎不是csv。你能给我们看几行吗?我的意思是如果csv文件上的数据像狗、猫、青蛙。。然后,新的csv文件应该显示1_dog这样的值,看起来您在如何打开文件以及如何使用
csv
模块方面有问题。首先让你的代码在django外部工作,然后你可能有机会在django内部工作…
1_dog 1_cat 1_frog
似乎不是csv。你能给我们看几行吗?我的意思是如果csv文件上的数据像狗、猫、青蛙。。然后,新的csv文件应该显示1_dog这样的值,看起来您在如何打开文件以及如何使用
csv
模块方面有问题。首先让你的代码在django外部工作,然后你可能有机会在django内部工作…
1_dog 1_cat 1_frog
似乎不是csv。你能给我们看几行吗?我的意思是如果csv文件上的数据像狗、猫、青蛙。。然后,新的csv文件应该显示1_dog这样的值,看起来您在如何打开文件以及如何使用
csv
模块方面有问题。首先让您的代码在django外部工作,然后您可能有机会让它在django内部工作。。。