1

I'm comparing two files and writing difference to a third file.

I'm not able to open the files because (possibly) there is a \r in the path name. This is being run on a work computer and my username is robk that I think is the problem.

The Error:

OSError: [Errno 22] Invalid argument: Users\robk\\Downloads\\AR_New_Records.csv'

Here is my code. The problem comes from two last lines.

def read_items(filename):
    with open(filename) as fh:
        return {line.strip() for line in fh}

def diff_string(old, new):
    return "\n".join(
        ['[-] %s' % gone for gone in old - new] +
        ['[+] %s' % added for added in new - old]
    )

with open('Users\robk\Downloads\AR_New_Records.csv', 'w') as fh:    
fh.write(diff_string(read_items('Users\robk\Downloads\latestroster.csv')), read_items('Users\robk\Downloads\oldroster.csv'))

Any help would be appreciated!

Son Truong
  • 13,661
  • 5
  • 32
  • 58
RobK
  • 123
  • 1
  • 10

2 Answers2

1

I believe your error is caused by an invalid file path. You are currently using a relative path. Try:

with open('C:/Users/rkrouse/Downloads/AR_New_Records.csv', 'w') as fh:    
fh.write(diff_string(read_items('C:/Users/rkrouse/Downloads/latestroster.csv'), read_items('C:/Users/rkrouse/Downloads/oldroster.csv')))

I switched your relative paths to full paths. Also, switched backslash to forward slashes.

CSBatchelor
  • 174
  • 6
  • that is giving me a SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \uxxxxxxxx escape – RobK Sep 01 '18 at 06:05
  • actually i take that back. with the forward slashes instead of the back slashes, it now gives me a TypeError: diff_string() missing 1 required positional argument: 'new' – RobK Sep 01 '18 at 06:08
  • It looks like there is a parenthesis after the first read_items() call that should be moved to the end of the line. – CSBatchelor Sep 01 '18 at 06:14
0

Use raw string like:

r'Users\robk\Downloads\AR_New_Records.csv'

Or escape \:

'Users\\robk\\Downloads\\AR_New_Records.csv'
Austin
  • 25,759
  • 4
  • 25
  • 48
  • i did try both of those, and i'll make sure to update my the body of my question. I get FileNotFoundError: [Errno 2] No such file or directory: 'Users\\rkrouse\\Downloads\\AR_New_Records.csv' – RobK Sep 01 '18 at 05:58
  • @RobK: You might need to shift to absolute path not a relative one. – Austin Sep 01 '18 at 06:01