Computational BIM Community (from bimsg.org)

Wednesday, 10 June 2020

CSV to TSV & TTL

I've tested with Python 2.7, under Visual Studio Code .
Convert csv to tsv:
import csv

with open('Directory\filename.csv','r') as csvin, open('Directory\filename.txt', 'w') as tsvout:
    csvin = csv.reader(csvin)
    tsvout = csv.writer(tsvout, delimiter='\t')

    for row in csvin:
        tsvout.writerow(row)


Convert csv to ttl:
#!/usr/bin/env python

#import the CSV module for dealing with CSV files
import csv

#create a 'reader' variable, which allows us to play with the contents of the CSV file
#in order to do that, we create the ifile variable, open the CSV file into that, then pass its' contents into the reader variable.
ifile = open('Directory\filename..csv', 'rb')
reader = csv.reader(ifile)

#create a new variable called 'outfile' (could be any name), which we'll use to create a new file that we'll pass our TTL into.
outfile = open('Directory\filename.ttl', 'a')

#get python to loop through each row in the CSV, and ignore the first row.
rownum = 0
for row in reader:
if rownum == 0: # if it's the first row, then ignore it, move on to the next one.
pass
else: # if it's not the first row, place the contents of the row into the 'c' variable, then create a 'd' variable with the stuff we want in the file.
c = row
d = '<' + c[0] + c[1] + '> a pol:Council ;\n core:preferredLabel "' + c[2] + '" ;\n core:sameAs <' + c[3] + '> .\n \n'
outfile.write(d) # now write the d variable into the file
rownum += 1 # advance the row number so we can loop through again with the next row

# finish off by closing the two files we created

outfile.close()
ifile.close()

Source: https://github.com/r4isstatic/csv-to-ttl/blob/master/csv-ttl-convert-v1.py

3 comments:

  1. I am impressed by the information that you have on this blog. It shows how well you understand this subject.
    data analytics course
    big data analytics malaysia
    big data course

    ReplyDelete
  2. Thanks for such a great post and the review, I am totally impressed! Keep stuff like this coming.
    data science course

    ReplyDelete
  3. I was very pleased to find this site.I wanted to thank you for this great read!! I definitely enjoying every little bit of it and I have you bookmarked to check out new stuff you post.
    360DigiTMG PMP certification

    360DigiTMG PMP certification in Malaysia

    360DigiTMG PMP course in Malaysia

    360DigiTMG PMP course

    360DigiTMG PMP training in Malaysia

    ReplyDelete