Created
October 5, 2022 15:41
-
-
Save edoardottt/31f2b062190928eba2698649418c7866 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sys,csv | |
table_name="nome_tabella" | |
values="(column1, column2, column3, ...)" | |
# INSERT INTO table_name | |
#VALUES (value1, value2, value3, ...), | |
#(value1, value2, value3, ...), | |
#(value1, value2, value3, ...); | |
def main(filename,colonna): | |
f = csv.reader(open(filename)) | |
header = next(f) | |
num_colonne = len(header) | |
if colonna >= num_colonne: | |
print("La colonna {} non esiste. Il numero di colonne è {} (Da 0 a {}).".format(colonna, num_colonne, num_colonne-1)) | |
sys.exit() | |
result="INSERT INTO " + table_name + " " | |
result+=values + " VALUES " | |
for line in f: | |
result+="(" + line[colonna]+ ")," | |
result=result[:-1]+";" | |
with open("query.sql", "w+") as f: | |
f.write(result) | |
print("Fatto.") | |
if __name__ == '__main__': | |
usage='''utilizzo: python {} fileinput x | |
dove:\n | |
- fileinput è la locazione del file su disco | |
- x è la colonna del csv da esportare (partendo da 0) | |
'''.format(sys.argv[0]) | |
args = sys.argv[1:] | |
if(len(args) != 2): | |
print(usage) | |
sys.exit(1) | |
try: | |
test = int(args[1]) | |
except: | |
print(usage) | |
sys.exit(1) | |
main(args[0],int(args[1])) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment