[Tutor] Help with printing to text file

Chelsea G cegarcia0323 at gmail.com
Mon Feb 1 09:07:22 EST 2016


Hi,

So I am trying to get my function search to print  in a text file, but I
can only get it to print to Powershell. I have tried several things to get
it to print in its own text file but nothing I have tried is working. Can
someone tell me what I am doing wrong?

import csvimport sysimport jsonfrom collections import defaultdictfrom
collections import Counter
data = defaultdict(list)
mydict = defaultdict(list)
class dictionary:
	def __init__(self):
		self.dict = defaultdict(list)
		self.counted_dict = defaultdict(list)
		self.grouped_dict = defaultdict(list)
		self.other_dict = defaultdict(list)
		self.final_dict = defaultdict(list)
		self.total_dict = defaultdict(list)
		self.search_dict = defaultdict(list)
		
		
	def populate_dict(self, filename):	
		with open('weekly_test.csv', 'rb') as f:
			reader = csv.reader(f)
			next(reader, None)
			for row in reader:
				self.dict[row[2]].append(row[3])
			
	
	def total_counts(self):
		for key in self.dict.keys():
			total = 0
			b = Counter(self.dict[key])
			for value in b:
				total += b[value]
				self.total_dict.update({key: str(total)})
		
	def all_counts(self):
		data_count = Counter()
		for key in self.dict.keys():
			self.counted_dict.update({key: Counter(self.dict[key])})
			
	
	def grouped_counts(self):
		for key in self.dict.keys():
			total = 0
			c = Counter(self.dict[key])
			for value in c:
				if c[value] >= 5:
					self.grouped_dict.update({value: key + ': ' + str(c[value])})
				
				elif c[value] <= 4:
					
					total += c[value]
					self.other_dict.update({key: 'other: ' + str(total)})
	
			self.final_dict = self.grouped_dict, self.other_dict, self.total_dict			
				
	def json_output(self):
		with open ('weekly2.txt', 'w') as text_file:
			json.dump(self.final_dict, text_file, sort_keys = True, indent = 4)
			
	def search(self, filename):
		with open('weekly_test.csv', 'r') as searchfile:
			for line in searchfile:
				if 'PBI 43125' in line:
					print line
		with open('testdoc.txt', 'w') as text_file
			text_file = searchfile


More information about the Tutor mailing list