Jul-12-2023, 12:58 AM
You could do that like this. First I need a dictionary containing some data:
# open any old text file mytext = '/home/pedro/summer2023/breakingnewsenglish/UK_rationing.txt' with open(mytext) as t: data = t.readlines() print('data list is', len(data), 'long') # make a dictionary # all the keys are integers in this case, all the values are lines of text mydict = {i:data[i] for i in range(len(data))} # show the content of mydict for item in mydict.items(): print(item)Now get some data from the dictionary and put it in a list
# an empty list to take the dictionary items you want to save in a text file mylist = [] # just get the first 9 lines for i in range(10): mylist.append(mydict[i]) # show the things to be saved to text for m in mylist: print(m)Now make the list into a string and write the string to the text file
# join the list to a string # it is better to make a list than to create strings # strings take up much more memory because they persist, so I have been told mystring = ''.join(mylist) # write the string to a text file dict2text = '/home/pedro/summer2023/breakingnewsenglish/UK_rationing_part.txt' with open(dict2text, 'w') as out: out.write(mystring) print('Some text from a dictionary saved as', dict2text)3 steps to heaven! have fun learning!