Skip to content

Instantly share code, notes, and snippets.

@aleksandar-babic
Last active December 8, 2017 16:50
Show Gist options
  • Save aleksandar-babic/73b2312c67fd010591a1da7deaeb5fa3 to your computer and use it in GitHub Desktop.
Save aleksandar-babic/73b2312c67fd010591a1da7deaeb5fa3 to your computer and use it in GitHub Desktop.
301 Generator from CSV file
import csv
import sys
def parseLinks(fileName):
redirectsList = []
with open(fileName, 'rb') as f:
reader = csv.reader(f)
next(reader, None) # Skip CSV file headers
for row in reader:
destination = row[3].split(' ')[0]
if(destination[0] == '/'):
redirectsList.append('Redirect 301 {0} https://softworksai.com{1}'.format(row[0], destination))
return redirectsList
def writeHtaccess(redirectsList, fileName):
with open(fileName, 'w') as f:
comment = '##\n # Redirects from {0}\n##\n'.format(fileName)
f.write(comment)
for redirect in redirectsList:
f.write(redirect + '\n')
def main(argv):
if len(sys.argv) != 3:
print 'Usage: 301Generator.py csvFileName outputFileName'
sys.exit(1)
try:
redirects = parseLinks(sys.argv[1])
writeHtaccess(redirects, sys.argv[2])
print 'All redirects from {0} have been written to file {1}'.format(sys.argv[1], sys.argv[2])
except IOError as e:
print 'I/O error({0}): {1}'.format(e.errno, e.strerror)
sys.exit(2)
except:
print 'Unexpected error'
sys.exit(2)
if __name__ == '__main__':
main(sys.argv)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment