简体   繁体   中英

rar file module not working in python 2.7

i have a code like this

import rarfile
pwd = None
rar = rarfile.RarFile(source_filename)
rar.extractall(dest_dir,None,pwd)  # error from here

this code in working in ubuntu. when i run this on windows i get error like this

Traceback (most recent call last):
  File "1_bete_rar.pyw", line 132, in extract
  File "1_bete_rar.pyw", line 176, in unrar_file
  File "rarfile.pyc", line 586, in extractall
  File "rarfile.pyc", line 1112, in _extract
  File "rarfile.pyc", line 1704, in custom_popen
  File "subprocess.pyc", line 711, in __init__
  File "subprocess.pyc", line 948, in _execute_child
WindowsError: [Error 2] The system cannot find the file specified

what is the problem with my code? how can i extract rar file with python in windows?

As the rarfile FAQ states (and as is made evident by traces of subprocess in the stack trace),

[rarfile] depends on unrar command-line utility to do the actual decompression.

Note that by default it expect it to be in PATH. If unrar launching fails, you need to fix this.

So get UnRAR from http://www.rarlab.com/rar_add.htm and put it somewhere in your PATH (such as the directory you're running your script from).

Looks like source_filename isn't pointing to a valid RAR file, do this little check before, just to be sure:

import os.path
os.path.isfile(source_filename) # what's the value returned?

If the file exists, then check if the path is in the correct format. For example, this won't work:

source_filename = 'c:\documents\file.rar'

Try this instead:

source_filename = 'c:\\documents\\file.rar'

Or even better, use raw strings :

source_filename = r'c:\documents\file.rar'

One common problem using python with Windows is that the path separator is \\, but this is a special character that needs to be escaped in Python. If you print the source_filename you should be able to see if this is set correctly.

eg

source_filename = 'c:\users\prosserc\documents\myfile.txt'

will not work correctly. Here are a couple of alternatives:

Use a raw string:

source_filename = r'c:\users\prosserc\documents\myfile.txt'

or use os.path.join to join to an eviornment variable such as user_profile

source_filename = os.path.join(os.getenv('userprofile'), 'documents', 'myfile.txt')

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