简体   繁体   中英

OSError: [Errno 22] Invalid argument Python File Processing

i am currently undergoing my A2 studies in Computer Science and i am having difficulties with random access file processing.

I am trying to have a list UsersArray which stores some record data types UsersArray = [lion,soso,Sxia] and loop through the list and store each record in the File TEST.DAT at a specific offset calculated like this Address = hash(UsersArray[i].Password) . The problem occurs when i try to do File.seek(Address) . It gives me an error and tells me the argument in seek() function is not correct, and i don't understand why this error occurs.

import Users,pickle

File = open("TEST.DAT","rb+")

lion = Users.Users()
lion.Password = "ilovefood"
soso = Users.Users()
soso.Password = "cats123"
Sxia = Users.Users()
Sxia.Password = "luca<3"

UsersArray = [lion,soso,Sxia]

for i in range(3):
    Address = hash(UsersArray[i].Password)
    File.seek(Address)
    pickle.dump(UsersArray[i],File)

File.close()

Error Message:

    Traceback (most recent call last):
  File "C:\Users\Vaio\Desktop\PythonA2\File Processing\RandomAccessWrite.py", line 17, in <module>
    File.seek(Address)
OSError: [Errno 22] Invalid argument
[Finished in 0.1s with exit code 1]
[shell_cmd: python -u "C:\Users\Vaio\Desktop\PythonA2\File Processing\RandomAccessWrite.py"]
[dir: C:\Users\Vaio\Desktop\PythonA2\File Processing]
[path: C:\MinGW\bin;C:\Users\Vaio\AppData\Local\Programs\Python\Python36-32\Scripts\;C:\Users\Vaio\AppData\Local\Programs\Python\Python36-32\]

Thank you for the help in advance!

I am inclined to believe that jasonharper nailed the issue. I replicated your code using my own user objects and commented out the pickle.dump() line. I was able to print both the user with the corresponding hash value without any issues. Then I uncommented pickle.dump() and used my own (small) iterative value to use in File.seek() ; when I did this, everything worked fine and python wrote to the file. I think the hash values that you're calculating are too large to be written to the file. Not sure if it's part of your assignment or not, but those hash values won't work as file offsets.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM