Advertisement
robertvari

txt_to_excell

May 31st, 2019
230
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.42 KB | None | 0 0
  1. import os, re, xlsxwriter
  2.  
  3. def main(folderPath, outputFile):
  4.     '''
  5.    :param folderPath: Where text files are
  6.    :param outputFile: Where excel file goes
  7.    :return: None
  8.    '''
  9.     # get all files
  10.     files = [os.path.join(folderPath, i) for i in os.listdir(folderPath) if i.endswith(".txt")]
  11.  
  12.     data_dict = find_names(files)
  13.     createTable(data_dict, outputFile)
  14.  
  15. def find_names(files):
  16.     return_dict = {}
  17.  
  18.     for textFile in files:
  19.         with open(textFile) as txt:
  20.             content = txt.read()
  21.  
  22.             result = re.findall(r'a\) neve: (.*)', content)
  23.  
  24.             if result:
  25.                 return_dict[textFile] = []
  26.  
  27.                 for text in result:
  28.                     # text_list = [i.strip() for i in text.split(",")]
  29.                     return_dict[textFile].append(text)
  30.  
  31.     return return_dict
  32.  
  33. def createTable(data_dict, outFile):
  34.     workbook = xlsxwriter.Workbook(outFile)
  35.     worksheet = workbook.add_worksheet()
  36.  
  37.     # Widen the first column to make the text clearer.
  38.     worksheet.set_column('A:A', 50)
  39.  
  40.     counter = 0
  41.     for fileName, names in data_dict.items():
  42.         worksheet.write(counter, 0, fileName)
  43.  
  44.         for index, name in enumerate(names):
  45.             worksheet.write(counter, index+1, name)
  46.  
  47.         counter += 1
  48.  
  49.     workbook.close()
  50.  
  51. main(r"E:\_PythonSuli\0413\Master1\text_to_excel", r"E:\_PythonSuli\0413\Master1\text_to_excel\names.xlsx")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement