so I got this function here, and what it's supposed to do is create a file, that I can write in. the second and third parameters are lists, while the first is just the file name that I am going to create to write in. In the function, I made a for loop, and I'm looping through the all_students_list, which is a list, but at each index, is also a list, with the first name and last name in the list. all_courses_list is a list of all the courses in the school, and Schedule is a list that another function returns, giving us the schedule of the student. Then I added the student name and the schedule together, to write to the file. The problem is that it also prints [] square brackets. How can I get rid of it? I've already tried to do
.replace('[', '')
.replace(']', '')
But it doesn't work.
Here is my code.
def generate_student_schedules(filename, all_courses_list, all_students_list):
with open(filename,'w') as fileout:
for one_student in all_students_list:
schedule = get_schedule(all_courses_list)
one_line = ''
one_line += (f'{one_student}')
one_line += (f'{schedule}\n')
fileout.write(one_line)
If one_student is an actual list, then you can use " ".join(one_student), so overall:
def generate_student_schedules(filename, all_courses_list, all_students_list):
with open(filename,'w') as fileout:
for one_student in all_students_list:
schedule = get_schedule(all_courses_list)
one_line = ''
one_line += (" ".join(one_student))
one_line += (f'{schedule}\n')
fileout.write(one_line)
When you print a list, Python's default is to print the brackets and items in the list. You have to build a single string of the components of the list and print that single string. Your format string can pull out individual items or use join across all the items if they are all strings:
>>> student = ['John','Smith']
>>> schedule = ['Class1','Class2']
>>> print(student,schedule)
['John', 'Smith'] ['Class1', 'Class2']
>>> line = f'{student[1]}, {student[0]}: {", ".join(schedule)}'
>>> print(line)
Smith, John: Class1, Class2
Related
This is my first post, so if I miss something, let me know.
I'm doing a CS50 beginner python course, and I'm stuck with a problem.
Long story short, the problem is to open a csv file, and it looks like this:
name,house
"Abbott, Hannah",Hufflepuff
"Bell, Katie",Gryffindor
.....
So I would love to put into a dictionary (which I did), but the problem now is that I supposed to split the "key" name in 2.
Here is my code, but it doesn't work:
before = []
....
with open(sys.argv[1]) as file:
reader = csv.reader(file)
for name, house in reader:
before.append({"name": name, "house": house})
# here i would love to split the key "name" in "last", "first"
for row in before[1:]:
last, first = name.split(", ")
Any advice?
Thank you in advance.
After you have the dictionary with complete name, you can split the name as below:
before = [{"name": "Abbott, Hannah", "house": "Hufflepuff"}]
# Before split
print(before)
for item in before:
# Go through each item in before dict and split the name
last, first = item["name"].split(', ')
# Add new keys for last and first name
item["last"] = last
item["first"] = first
# Remove the full name entry
item.pop("name")
# After split
print(before)
You can also do the split from the first pass, e.g. store directly the last and first instead of full name.
I have a list of first name, last name, and score in a text file that refers to a student and their test score. When I go to sort them so I can find the median score, it only returns from the sort() the last grade on the list. I need it to return all of them, but obviously sorted in order. Here is the part of my code in question:
def main():
#open file in read mode
gradeFile = open("grades.txt","r")
#read the column names and assign them to line1 variable
line1 = gradeFile.readline()
#tell it to look at lines 2 to the end
lines = gradeFile.readlines()
#seperate the list of lines into seperate lines
for line in lines:
#initialize grades list as an empty list
gradeList = []
#iterate through each line and take off the \n
line = line.rstrip()
line = line.split(",")
grades = line[-1]
try:
gradeList.append(float(grades))
except ValueError:
pass
#print(gradeList)
#sort the grades
gradeList.sort(reverse=False)
print(gradeList)
You clear the list each time the loop runs. Move the assignment outside the loop.
I have two wordlists, as per examples below:
wordlist 1 :
code1
code2
code3
wordlist 2 :
11
22
23
I want to take wordlist 2 and put every number in a line with first line in wordlist 1
example of the output :
code111
code122
code123
code211
code222
code223
code311
.
.
Can you please help me with how to do it? Thanks!
You can run two nested for loops to iterate over both lists, and append the concatenated string to a new list.
Here is a little example:
## create lists using square brackets
wordlist1=['code1', ## wrap something in quotes to make it a string
'code2','code3']
wordlist2=['11','22','23']
## create a new empty list
concatenated_words=[]
## first for loop: one iteration per item in wordlist1
for i in range(len(wordlist1)):
## word with index i of wordlist1 (square brackets for indexing)
word1=wordlist1[i]
## second for loop: one iteration per item in wordlist2
for j in range(len(wordlist2)):
word2=wordlist2[j]
## append concatenated words to the initially empty list
concatenated_words.append(word1+word2)
## iterate over the list of concatenated words, and print each item
for k in range(len(concatenated_words)):
print(concatenated_words[k])
list1 = ["text1","text2","text3","text4"]
list2 = [11,22,33,44]
def iterativeConcatenation(list1, list2):
result = []
for i in range(len(list2)):
for j in range(len(list1)):
result = result + [str(list1[i])+str(list2[j])]
return result
have you figured it out? depends on if you want to input the names on each list, or do you want it to for instance automatically read then append or extend a new text file? I am working on a little script atm and a very quick and simple way, lets say u want all text files in the same folder that you have your .py file:
import os
#this makes a list with all .txt files in the folder.
list_names = [f for f in os.listdir(os.getcwd()) if f.endswith('.txt')]
for file_name in list_names:
with open(os.getcwd() + "/" + file_name) as fh:
words = fh.read().splitlines()
with open(outfile, 'a') as fh2:
for word in words:
fh2.write(word + '\n')
I am reading a list of states from a file into an list[]:
mystk = []
with open('state_list.txt') as csvfile:
readCSV = csv.reader(csvfile,delimiter=',')
for row in readCSV:
mystk.append(row)
After the read I am adding the values in to a list.
print(str(mystk[0]).strip())
i=0
while i < 10:
strList = mystk[i]
print('Print:',strList)
i = i +1
The output of the above is :
Print: ['AL']
Print: ['AK']
Print: ['AZ']
Print: ['AR']
Print: ['CA']
Print: ['CO']
Print: ['CT']
Print: ['DE']
Print: ['FL']
Print: ['GA']
I am trying to achieve the following:
Print: AL
Print: AK
Print: AZ
Print: AR
Print: CA
Print: CO
Print: CT
Print: DE
Print: FL
Print: GA
I guess I could write a function or loop to strip out the ['?'] using regex or code like this:
i=0
while i < 10:
strList = mystk[i]
strList = str(strList).replace("['", "")
strList = strList.replace("']", "")
print(' ','Print:',strList)
i = i +1
However I was hoping there was an easier way then the code above however I am new to python and if this is the only way then it works for me.
this are recommendations that I mention in my comment plus some other
import csv
def getTID(file='TID.csv', delim='\n'):
result = []
with open(file) as csvTID:
readCSV = csv.reader(csvTID, delimiter=delim)
for row in readCSV:
result.append( row[0] )
return result
stockList = getTID()
for x in stockList:
print(x)
here with the use of arguments give the function more flexibility and with default values I retain the original behavior that way you don't need to modify your code (or the name of the file) if you want to use your function with another file like 'TID_2.cvs' for example, in that case just call getTID('TID_2.cvs') and as the function don't do anything to some global variable you can have the data from 2 or more different files in different variables if you need it, for example
stockList1 = getTID('TID_1.cvs')
stockList2 = getTID('TID_2.cvs')
every line of the csv file is split by commas, to get the string joined by commas again, use str.join:
sep = ", "
for row in mystk:
print(' ', 'Print:', sep.join(row))
Guys thank you all very much, learning this is stuff is awesome. So many ways to do stuff. After reading your comments and understanding the concepts I have written the following function to get the stock list I need:
import csv
stockList = []
def getTID():
with open('TID.csv') as csvTID:
readCSV = csv.reader(csvTID,delimiter='\n')
for row in readCSV:
stockList.append((row[0]))
getTID()
for x in stockList[:]: print(x)
This returns the list as expected: VOD.L, APPL, etc.
I need to make a program in a single def that opens a text file 'grades' where first, last and grade are separated by comas. Each line is a separate student. Then it displays students and grades as well as class average. Then goes on to add another student and grade and saves it to the text file while including the old students.
I guess I just don't understand the way python goes through the text file. If i comment out 'lines' I see it prints the old_names but its as if everything is gone after. When lines is not commented out 'old_names' is not printed which makes me think the file is closed? or empty? however everything is still in the txt file as it should be.
currently i get this error.... Which I am pretty sure is telling me I'm retarded there's no information in 'line'
File "D:\Dropbox\Dropbox\1Python\Batch Processinga\grades.py", line 45, in main
first_name[i], last_name[i], grades[i] = line.split(',')
ValueError: need more than 1 value to unpack
End goal is to get it to give me the current student names and grades, average. Then add one student, save that student and grade to file. Then be able to pull the file back up with all the students including the new one and do it all over again.
I apologize for being a nub.
def main():
#Declare variables
#List of strings: first_name, last_name
first_name = []
last_name = []
#List of floats: grades
grades = []
#Float grade_avg, new_grade
grade_avg = new_grade = 0.0
#string new_student
new_student = ''
#Intro
print("Program displays information from a text file to")
print("display student first name, last name, grade and")
print("class average then allows user to enter another")
print("student.\t")
#Open file “grades.txt” for reading
infile = open("grades.txt","r")
lines = infile.readlines()
old_names = infile.read()
print(old_names)
#Write for loop for each line creating a list
for i in len(lines):
#read in line
line = infile.readline()
#Split data
first_name[i], last_name[i], grades[i] = line.split(',')
#convert grades to floats
grades[i] = float(grades[i])
print(first_name, last_name, grades)
#close the file
infile.close()
#perform calculations for average
grade_avg = float(sum(grades)/len(grades))
#display results
print("Name\t\t Grade")
print("----------------------")
for n in range(5):
print(first_name[n], last_name[n], "\t", grades[n])
print('')
print('Average Grade:\t% 0.1f'%grade_avg)
#Prompt user for input of new student and grade
new_student = input('Please enter the First and Last name of new student:\n').title()
new_grade = eval(input("Please enter {}'s grade:".format(new_student)))
#Write new student and grade to grades.txt in same format as other records
new_student = new_student.split()
new_student = str(new_student[1] + ',' + new_student[0] + ',' + str(new_grade))
outfile = open("grades.txt","w")
print(old_names, new_student ,file=outfile)
outfile.close()enter code here
File objects in Python have a "file pointer", which keeps track of what data you've already read from the file. It uses this to know where to start looking when you call read or readline or readlines. Calling readlines moves the file pointer all the way to the end of the file; subsequent read calls will return an empty string. This explains why you're getting a ValueError on the line.split(',') line. line is an empty string, so line.split(",") returns a list of length 0, but you need a list of length 3 to do the triple assignment you're attempting.
Once you get the lines list, you don't need to interact with the infile object any more. You already have all the lines; you may as well simply iterate through them directly.
#Write for loop for each line creating a list
for line in lines:
columns = line.split(",")
first_name.append(columns[0])
last_name.append(columns[1])
grades.append(float(columns[2]))
Note that I'm using append instead of listName[i] = whatever. This is necessary because Python lists will not automatically resize themselves when you try to assign to an index that doesn't exist yet; you'll just get an IndexError. append, on the other hand, will resize the list as desired.