2

I'm using python 2.7 on windows platform. (I don't have a choice to upgrade - cannot import any non standard modules...work constraints.) I have written a csv file from a feature class. I then am attempting to re-format text in a column. For some reason I am unable to open the csv.

I get the following errors:

D:\JJ_Development\Projects\Basemap\Transportation>new.py
D:\JJ_Development\Projects\Basemap\Transportation
Traceback (most recent call last):
  File "D:\JJ_Development\Projects\Basemap\Transportation\new.py", line 199, in <module>
    newlabel()
  File "D:\JJ_Development\Projects\Basemap\Transportation\new.py", line 97, in newlabel
    with open(rc_existing, 'rb') as csvfile:
IOError: [Errno 2] No such file or directory: 'D:\\JJ_Development\\Projects\\Basemap\\Transportation\\roadcore'
  • Both the csv and the python script are in my current working directory.
  • The csv is not read only.
  • I can open the csv in both notepad++ and arcmap with no issues.
  • The file is not locked...I have restarted computer and have changed the name as well as copying over a fresh script.

I'm posting a snippet of csv creations (works) and then errors on the line "with open" (obviously this is not the full code)

    #********DATA AND PATHS********
curr_dir = os.getcwd()
print(curr_dir)
arcpy.env.workspace = (curr_dir)

#mxd = arcpy.mapping.MapDocument(r'D:\JJ_Development\Projects\Basemap\Transportation\Labels.mxd')
#in_fc = arcpy.mapping.ListLayers(mxd, 'RoadCore_test2')[0]
fc = (r'D:\JJ_Development\Projects\Basemap\Transportation\Roads.gdb\RoadCore_Existing')

fields = ["ID", "ADMIN_ORG", "RTE_CN", "GIS_MILES"]
identical = ["ID", "ADMIN_ORG", "RTE_CN"]
labels = []

rd_names = (' ROAD', ' STREET', ' DRIVE', ' BLUFF', ' COVE',' LOOP', ' LANE', ' RD', ' LN', ' DR')


#********Initial FS Roadcore Existing Data Cleanup********
rc_existing = os.path.join(curr_dir, 'roadcore')

def test():
    fields = ["ID", "ADMIN_ORG", "RTE_CN", "GIS_MILES"]

    with open('{}.csv'.format(rc_existing), 'wb') as outf:
        dw = csv.DictWriter(outf, fieldnames=fields)
        dw.writeheader()
        with arcpy.da.SearchCursor(fc, fields) as rows:
            for row in rows:
                if row[3] == 0:
                    pass
                elif row[3] == None:
                    pass
                else:
                    dw.writerow(dict(zip(fields, row)))
    print "File written: {}".format(rc_existing)
    outf.close()


#********FORMATTING LABELS********
def newlabel():
    with open(rc_existing, 'rb') as csvfile:
        reader = csv.reader(csvfile, delimiter=',', quotechar='|')
        for row in reader:
            print('csv open')

    # with arcpy.da.SearchCursor(rc_existing, fields) as sc:
        # for row in sc:
            # if (row[0].startswith(' ')):
                # labels.append('{}'.format(row[0].replace(' ', '')))

if __name__ == '__main__':
    test()
    newlabel()
1
  • So, in the error message you posted first, you're opening the file in mode rb, which is read-only/binary. Then later in the code, at the line with open('{}.csv, you're opening it in mode wb, which is write-only/binary. There's a list of codes available to you here. Are you sure you're opening it in the correct mode? What if you tried, simply, mode r? (If you're going to write in the file, try r+.)
    – elrobis
    Commented Aug 5, 2020 at 16:26

1 Answer 1

1

I was trying to do automated 'in line' edits with my open csv file. Evidently that is not possible. For this script to function I needed to create a temporary file for editing and use shutil.move to make write the temp file to permanent.

Lessons learned:

  • You may get a blank space in between each line (I did) if you do not use binary mode. Thanks elrobis for response but that wasn't the issue.
  • You may get a comma in between each output character if you use plural 'writerows' instead of 'writerow'.

Posting operable relevant code snippet here if anyone wants reference.

#********DATA AND PATHS********
curr_dir = os.getcwd()
print(curr_dir)
arcpy.env.workspace = (curr_dir)

fc = (r'D:\JJ_Development\Projects\Basemap\Transportation\Roads.gdb\RoadCore_Existing')

rc_existing = os.path.join(curr_dir, 'roadcore')
roadcore = r'D:\JJ_Development\Projects\Basemap\Transportation\roadcore.csv'


fields = ["ID", "ADMIN_ORG", "RTE_CN", "GIS_MILES"]
identical = ["ID", "ADMIN_ORG", "RTE_CN"]
labels = []

rd_names = (' ROAD', ' STREET', ' DRIVE', ' BLUFF', ' COVE',' LOOP', ' LANE', ' RD', ' LN', ' DR')

#********Initial FS Roadcore Existing Data Cleanup********

def test():
    fields = ["ID", "ADMIN_ORG", "RTE_CN", "GIS_MILES"]
    with open('{}.csv'.format(rc_existing), 'wb') as outf:
        dw = csv.DictWriter(outf, fieldnames=fields)
        dw.writeheader()
        with arcpy.da.SearchCursor(fc, fields) as rows:
            for row in rows:
                if row[3] == 0:
                    pass
                elif row[3] == None:
                    pass
                else:
                    arcpy.DeleteIdentical_management(fc, identical)
                    dw.writerow(dict(zip(fields, row)))
    print "File written: {}".format(rc_existing)
    outf.close()

#********CREATE TEMP FILE FOR LABEL FORMATTING********
filename = roadcore
rc_temp = NamedTemporaryFile('w+b', delete=False)#default should be binary. Adding binary causes an os.unlink error. 

def temp_file():
    with open(filename, 'r') as csvFile, rc_temp:
        reader = csv.reader(csvFile, delimiter=',', quotechar='|')
        writer = csv.writer(rc_temp, delimiter=',', quotechar='|')
        for row in reader:
            if row[1] == None:
                pass
            elif row[0].startswith(' '):
                labels.append('{}'.format(
                                        row[0]
                                        .replace(' ', '')))
            elif row[1].startswith('01'):
                labels.append('{}'.format(
                                        row[0]
                                        .lstrip(ascii_letters)
                                        .replace(' ', '')
                                        .replace('.', '-')
                                        .lstrip('0')))
            elif row[1].startswith('02'):
                labels.append('{}'.format(
                                        row[0].lstrip(ascii_letters)
                                        .replace(' ', '')
                                        .replace('.', '-')
                                        .lstrip('0')))
            elif row[1].startswith('03'):
                labels.append('{}'.format(
                                        row[0]
                                        .lstrip(ascii_letters)
                                        .replace(' ', '')
                                        .replace('.', '-')
                                        .lstrip('0')))
            elif row[1].startswith('04'):
                labels.append('{}'.format(
                                        row[0]
                                        .lstrip(ascii_letters)
                                        .replace('-ADMIN', '')
                                        .replace('-A-ADMIN','')
                                        .replace('-PARKING','')[2:]
                                        .lstrip('0')
                                        .replace('.', '-')))
            elif row[1].startswith('05'):
                labels.append('{}'.format(
                                        row[0].rstrip('0')
                                        .lstrip('0')
                                        .lstrip(ascii_letters)
                                        .replace('.', '-')))
            elif row [1].startswith('0501'):
#Note: 0501 forest label data entered in unicode.
                labels.append('{}'.format(
                                        row[0].rstrip('0').split('.',1)
                                        .replace(' ', '')))
            elif row[1].startswith('06'):
                labels.append('{}'.format(
                                        row[0].rstrip('0')
                                        .replace('.', '-')
                                        .lstrip(ascii_letters)))
            elif (row[1].startswith('06')) and (row[0].endswith(rd_names)):#if id field contains rd names ASCII strip all alpha
                labels.append('{}'.format(
                                        row[0].rstrip(ascii_letters)))
            elif row[1].startswith('0816'):
                pass
            elif row[1].startswith('08'):
                labels.append('{}'.format(
                                        row[0].lstrip(ascii_letters)))
#Note: R08 label data entered in unicode.
            elif row[1].startswith('09'):
#Note: R09 label data entered in unicode.
                labels.append('{}'.format(
                                        row[0].lstrip('0')
                                        .replace('.', '-')
                                        .lstrip(ascii_letters)))
            elif row[1].startswith('10'):
                labels.append('{}'.format(
                                        row[0]
                                        .lstrip('0')
                                        .replace('.', '-')
                                        .lstrip(ascii_letters)))
            else:
                labels.append(row[0])
            writer.writerow(row)
    #print(labels)
    shutil.move(rc_temp.name, filename)
    print('Label formatting done')

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.