ValueError must have exactly one of create read write append mode

0 votes

Traceback (most recent call last):
  File "C:/ScriptsPython/pythonProject/Criar_Banco.py", line 16, in <module>
    with open(nome_arquivo, 'rw') as csvfile, arquivo_temp:
ValueError: must have exactly one of create/read/write/append mode

import csv
import shutil
from tempfile import NamedTemporaryFile

nome_arquivo = 'exemplo.csv'
arquivo_temp = NamedTemporaryFile(delete=False)

with open('exemplo.csv', 'r') as csvfile, arquivo_temp:
    reader = csv.DictReader(csvfile)
    campos = ['SUBSCRIBERID',
              'SERIALNUMBER',
              'DEVICE_TYPE_NAME',
              'FIRSTCONTACTTIME',
              'LASTCONTACTTIME',
              'LASTACTIVATIONTIME',
              'SOFTWAREVERSION',
              'EXTERNALIPADDRESS',
              'PRODUCT_CLASS',
              'MANUFACTURER',
              'OUI',
              'MODEL_NAME',
              'ACTIVATED',
              'DELETED',
              'NASIP',
              'NASPORT',
              'NRC',
              'REPLACED_BY',
              'SERVICETYPEID',
              'UPTIME',
              'FIRSTUSAGEDATE',
              'HARDWAREVERSION',
              'SPECVERSION',
              'PROVISIONCODE',
              'ADDITIONALHARDWAREVERSION',
              'ADDITIONALSOFTWAREVERSION',
              'VENDORCONFIGFILENUMBEROFENTRIES',
              'MACADDR',
              'MAC_5G']
    writer = csv.DictWriter(arquivo_temp, fieldnames=campos)
    writer.writeheader()
    for linha in reader:
        print(linha)
        if linha['PRODUCT_CLASS'] == 'HGU_Askey_Sophia':
            linha['MAC_5G'] = 'teste'
            print(linha)
        writer.writerow(linha)
    shutil.move(arquivo_temp.name, nome_arquivo)
Nov 15, 2020 in Python by Rajiv
• 8,870 points
3,622 views

1 answer to this question.

0 votes

You can open a file for simultaneous reading and writing but it won't work the way you expect:

with open('file.txt', 'w') as f:
    f.write('abcd')

with open('file.txt', 'r+') as f:  # The mode is r+ instead of r
    print(f.read())  # prints "abcd"

    f.seek(0)        # Go back to the beginning of the file
    f.write('xyz')

    f.seek(0)
    print(f.read())  # prints "xyzd", not "xyzabcd"!

You can overwrite bytes or extend a file but you cannot insert or delete bytes without rewriting everything past your current position. Since lines aren't all the same length, it's easiest to do it in two seperate steps:

lines = []

# Parse the file into lines
with open('file.txt', 'r') as f:
    for line in f:
        if line.startswith('text to replace'):
            line = 'new text\n'

        lines.append(line)

# Write them back to the file
with open('file.txt', 'w') as f:
    f.writelines(lines)

    # Or: f.write(''.join(lines))
answered Nov 15, 2020 by Gitika
• 65,770 points

Related Questions In Python

0 votes
1 answer

How to write content of one file to another file in Python?

The following code snippet might solve your ...READ MORE

answered Aug 26, 2019 in Python by Neel
• 3,020 points
789 views
+1 vote
0 answers

I have to write 2 triangles in one raw (python)

I have two triangles that has to ...READ MORE

Dec 4, 2019 in Python by מיקה
• 130 points
1,007 views
0 votes
1 answer

How to create Pandas series from numpy array?

Hi. Refer to the below command: import pandas ...READ MORE

answered Apr 1, 2019 in Python by Pavan
3,506 views
0 votes
1 answer
0 votes
1 answer

How to create Pandas series from dictionary?

Here's a sample script: import pandas as pd import ...READ MORE

answered Apr 1, 2019 in Python by Prateek
2,318 views
0 votes
2 answers
+7 votes
8 answers

What exactly is the function of random.seed() in python?

The seed method is used to initialize the ...READ MORE

answered Oct 29, 2018 in Python by Rahul
126,817 views
0 votes
1 answer

How do I check if a given Python string is a substring of another one?

Try using in like this: >>> x = 'hello' >>> y ...READ MORE

answered Nov 26, 2020 in Python by Gitika
• 65,770 points
748 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP