Last active
December 8, 2017 16:50
-
-
Save aleksandar-babic/73b2312c67fd010591a1da7deaeb5fa3 to your computer and use it in GitHub Desktop.
301 Generator from CSV file
This file contains 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 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