Я пытаюсь заставить python попросить пользователя открыть местоположение файла, откуда они хотели бы, чтобы данные считывались в фрейм данных.
Код, который я пробую:
import datetime
import pandas as pd
import json
import gc
import os
from pandas.io.json import json_normalize
Today = datetime.datetime.today() # Set Today string to today's name
Today_day = Today.strftime("d") # Set Today_day to the date in the month (e.g. 21)
while True:
user_input = input("Enter the path of your file (Remember to include the file name and extension): ") # Asks user for filepath of file to be used
if not os.path.isfile(user_input): # If filepath is not correct (e.g. missing or incorrect filename)
print() # Print a blank line
print("I did not find the file at "+str(user_input)) # Print that file was not found
print() # Print a blank line
continue # Goes back to asking for a correct filepath
else: # If filepath is correct
break # Break out of while loop
#iFile = open(user_input,'rt') # Opens file, if present, in read only mode ("r"), specifying that it is a text file ("t")
gc.collect() # Empty garbage collect
SIEBEL = pd.read_csv(user_input, encoding = "ISO-8859-1") # Get data from SIEBEL PSD2 extract
SIEBEL.fillna("", inplace = True) # Replace null values with blanks
SIEBEL.sort_values("CIF", inplace=True) # Sort dataframe by CIF values
print () # Print blank row
print (SIEBEL.dtypes)
print () # Print blank row
print ("SIEBEL extract contains:", len(SIEBEL.index), "rows") # Print number of rows in SIEBEL data
print ("SIEBEL extract contains:", len(SIEBEL.columns), "columns") # Print number of columns in SIEBEL data
SIEBEL.drop(columns=["Eircode"], axis=1, inplace=True) # Drops oa column, in this case Eircode from the dataframe
print () # Print blank row
print ("SIEBEL extract contains:", len(SIEBEL.columns), "columns") # Print number of rows in SIEBEL data
print ()
print (SIEBEL.dtypes) # Print all types in dataframe
SIEBEL.to_csv(r"C:\Users\LIDJ622\Desktop\SIEBEL_export"+Today.strftime("%B %#d")+".csv", index=None, header=True) # Save the sorted file as a CSV to the desktop
Однако, когда я пытаюсь это сделать, я получаю
runfile ('C: / Users / LIDJ622 / Desktop / Test 1 increment.py', wdir = 'C: / Users /LIDJ622 / Desktop ')
Введите путь к файлу (не забудьте указать имя файла и расширение): SIEBEL Extract 20k v1.csv Traceback (последний вызов был последним):
File "", строка 1, в исполняемом файле ('C: / Users / LIDJ622 / Desktop / Test 1 increment.py', wdir = 'C: / Users / LIDJ622 / Desktop')
Файл" C: \ ProgramData\ Anaconda3 \ lib \ site-packages \ spyder \ utils \ site \ sitecustomize.py ", строка 705, в исполняемом файле исполняемого файла (имя файла, пространство имен)
Файл" C: \ ProgramData \ Anaconda3 \ lib \ site- "packages \ spyder \ utils \ site \ sitecustomize.py ", строка 102, в execfile exec (compile (f.read (), filename, 'exec'), пространство имен)
Файл" C: / Users /LIDJ622 / Desktop / Test 1 increment.py ", строка35, в SIEBEL.sort_values ("CIF", inplace = True) # Сортировать фрейм данных по значениям CIF
Файл "C: \ ProgramData \ Anaconda3 \ lib \ site-packages \ pandas \ core \ frame.py", строка 3634, в sort_values na_position = na_position)
Файл "C: \ ProgramData \ Anaconda3 \ lib \ site-packages \ pandas \ core \ sorting.py", строка 250, в nargsort indexer = non_nan_idx [non_nans.argsort (kind = kind)] * 1023 *
TypeError: '<' не поддерживается между экземплярами 'str' и 'float' </p>
Как я могу заставить Python спросить, где пользовательфайл находится, а затем импортировать его в фрейм данных?
Редактировать: включен полный код и сообщение об ошибке