python - How to save each element of a list to an independent new file? -
i have function pos-tag number of documents , prints each pos-tagged document in list follows:
[u'i\tpp\ti', u'am\tvbp\tbe', u'an\tdt\tan', u'amateur\tjj\tamateur'] .... [u'good\tjj\tgood', u'camera\tnn\tcamera', u'for\tin\tfor', u'a\tdt\ta', u'good\tjj\tgood']
how can save or write each list new .txt document in new directory?, example:
new_directory ---->list1.txt .... ---->listn.txt
now, if inside each new file this:
good jj camera nn camera in dt jj
thanks in advance guys.
as 1 way can iterate on lists (i assumed they're in nested list here) , open file , write contents of list file.
you hardcode path appropriate seperators, used os.path.join here it's typically use this. how you're specifying new directory wasn't mentioned. take in sys.argv, file dialog, input, or other numerous options.
import os nested_list=[ [u'i\tpp\ti', u'am\tvbp\tbe', u'an\tdt\tan', u'amateur\tjj\tamateur'], [u'good\tjj\tgood', u'camera\tnn\tcamera', u'for\tin\tfor', u'a\tdt\ta', u'good\tjj\tgood'] ] i, a_list in enumerate(nested_list): #new_dir_path path dir want. path = os.path.join(new_dir_path, "list%d.txt" % i) #or "list{}.txt".format(i) open(path, "w") f: item in a_list: f.write(item+"\n") #\n if want each item on new line
Comments
Post a Comment