pythonpandascsvpasswordsrar

Generate Desktop path and open csv inside password protected RAR without leaving password trace in terminal [share my knowledge]


Answer my own question – share your knowledge, Q&A-style

I'm use a CSV file as Dataframe, but it's inside a password-protected RAR file on the Desktop.

As each user has a different name generating a different path to the Desktop, I will also generate the path automatically regardless of the user's name, so that I can use it on any computer with Windows without having to change the path string.

This will be my contribution to the StackOverflow community today!

Note: feel free to publish improved models for this need.


Solution

  • from rarfile import RarFile
    from getpass import getpass
    import pandas as pd
    import os
    
    desktop = os.environ['USERPROFILE'] + '\Desktop' # create desktop path
    
    rar_files = RarFile(desktop + '\archive_rar.rar', 'r') # open RAR file
    
    specific_file = rar_files.open('file_inside_rar.csv',pwd=getpass()) # open csv file that is inside RAR
    
    print('\033[A\033[A') # Clear row of the password request in the terminal
    
    df = pd.read_csv(specific_file) # Dataframe created from csv file
    
    print(df.iloc[0].values[0]) # row 0, value 0
    print(df.iloc[1].values[0]) # row 1, value 0
    print(df.iloc[2].values[0]) # row 2, value 0
    

    The string in the terminal will look like this:

    getpass() will ask you for the password of the RAR file:

    Password:
    

    You will type but the password text will not appear!

    When finished typing the password, press ENTER.

    Then print('\033[A\033[A') will clear the existing text in the terminal:

    
    

    then first print:

    row_1_value
    

    then second print:

    row_1_value
    row_2_value
    

    then third print:

    row_1_value
    row_2_value
    row_3_value