How to make data entered by user to appear below headers - python

This is my code for entering student details. Once the user has entered the details and inputs yes, the details are exported to StudentDetails.csv (Microsoft Excel) where it should go below the headers but ends up going somewhere else.
def EnterStudent():
uchoice_loop = False
ask_loop = False
while uchoice_loop == False:
surname = raw_input("What is the surname?")
forename = raw_input("What is the forname?")
date = raw_input("What is the date of birth? {Put it in the format D/M/Y}")
home_address = raw_input("What is the home address?")
home_phone = raw_input("What is the home phone?")
gender = raw_input("What is their gender?")
tutor_group = raw_input("What is their tutor group?")
email = (forename.lower() + surname.lower() + ("#school.com"))
print(surname+" "+forename+" "+date+" "+home_address+" "+home_phone+" "+gender+" "+tutor_group+" "+email)
ask = raw_input("Are these details correct?"+"\n"+"Press b to go back, or yes to add entered data on your student.").lower()
if ask == "yes":
f = open("StudentDetails.csv","rt")
lines = f.readlines()
f.close()
lines.append(surname+","+forename+","+date+","+home_address+","+home_phone+","+gender+","+tutor_group+","+email+"\n")
f = open("StudentDetails.csv", "w")
f.writelines(lines)
f.close()
uchoice_loop = True
printMenu()
elif ask == "b":
uchoice_loop = False
else:
print("Plesase enter 'b' to go back or 'yes' to continue")
This is my csv file.
enter image description here

There's a few things you can do to make this work. You dont need to open the StudentDetails.csv and read all of the lines. Instead you can make a lines string variable and append it the the StudentDetails.csv like in the example below
#f = open("StudentDetails.csv","rt")
#lines = f.readlines()
#f.close()
lines = surname+","+forename+","+date+","+home_address+","+home_phone+","+gender+","+tutor_group+","+email
# the "a" appends the lines variable to the csv file instead of writing over it like the "w" does
f = open("StudentDetails.csv", "a")
f.writelines(lines)
f.close()
uchoice_loop = True

Eric is right in that you best open the file in append-mode (see https://docs.python.org/3.6/library/functions.html#open) instead of cumbersomely reading and rewriting your file over and over again.
I want to add to this that you probably will enjoy using the standard library's csv module as well (see https://docs.python.org/3.6/library/csv.html), especially if you want to use your output file in Excel afterwards.
Then, I'd also advise you to not use variables for while loop conditionals, but learning about the continue and break statements. If you want to break out of the outer loop in the example, research try, except and raise.
Finally, unless you really have to use Python 2.x, I recommend you to start using Python 3. The code below is written in Python 3 and will not work in Python 2.
#!/usr/bin/env python
# -*- codig: utf-8 -*-
import csv
def enterStudent():
b_or_yes = 'Press b to go back, or yes to save the entered data: '
while True:
surname = input('What is the surname? ')
forename = input('What is the first name? ')
date = input(
'What is the date of birth? {Put it in the format D/M/Y} ')
home_address = input('What is the home address? ')
home_phone = input('What is the home phone? ')
gender = input('What is the gender? ')
tutor_group = input('What is the tutor group? ')
email = forename.lower() + surname.lower() + '#school.com'
studentdata = (
surname,
forename,
date,
home_address,
home_phone,
gender,
tutor_group,
email)
print(studentdata)
while True:
reply = input('Are these details correct?\n' + b_or_yes).lower()
if reply == 'yes':
with open('studentdetails.csv', 'a', newline='') as csvfile:
studentwriter = csv.writer(csvfile, dialect='excel')
studentwriter.writerow(studentdata)
break
elif reply == 'b':
break
if __name__ == '__main__':
enterStudent()
Best of luck!

Related

Writing a text file with rows that have two words separated by comma from a while loop

dictionary = {}
name = input("Name: ")
while name: #while the name is not blank
age = input("Age: ")
dictionary[name] = age
name = input("Name: ")
print("Thank you, bye!")
f = open("1ex.txt","w")
f.write( str(dictionary) )
f.close()
So I have this code, it does what I want, but I cant seems to figure it out how can I write the file, so that it would have not a dictionary, but smth like this:
Jane, 25
Jim, 24
I tried putting everything into a list, but it doesn't work out for me.
Try this:
dictionary = {}
name = input("Name: ")
while name: #while the name is not blank
age = input("Age: ")
dictionary[name] = age
name = input("Name: ")
print("Thank you, bye!")
# Open the file
with open("1ex.txt","w") as f:
# For each key/value pair in the dictionary:
for k, v in dictionary.items():
# Write the required string and a newline character
f.write(f"{k}, {v}\n")

How to read multiple lines from a text file and choose one to edit

I am a university student and have to prepare a lesson in Python to give to a class of year 9's. I have created an address book program which allows them to create an address book and add entries and view the book.
The one part I can't figure out is how to edit entries. You basically have to be able to pick one out of several lines and then type new data which will save over the original line.
When adding entries originally, I take in the name, age, address and city in separate variables and then write them to a text file with commas between them.
I wasn't sure what information to give over just yet as I don't usually use Stack Overflow so if you need any more information or code please just let me know!
Thank you!
David
Edit I've added all the code below. It prints to a text file and separates them by commas.
def createAddBook():
f = open("address_book.txt", "w")
def viewAddBook():
f = open("address_book.txt", "r")
contacts = f.read()
print(contacts)
print()
f.close
def addEntry():
addList = []
Name = input("What is the name?" + "\n")
Age = input("What is the age?" + "\n")
Address = input("What is the address?" + "\n")
City = input("What is the city?" + "\n")
addList.append(Name + ", ")
addList.append(Age + ", ")
addList.append(Address + ", ")
addList.append(City + "\n")
f = open("address_book.txt", "a")
for entry in addList:
f.write(entry)
f.close()
inuse = True
while inuse == True:
choice = input("Do you have an address book? (yes/no)" + "\n")
if choice == "yes":
choice = input("Would you like to view, add or edit your address book? (view/add/edit)" + "\n")
if choice == "view":
viewAddBook()
elif choice == "edit":
editEntry()
elif choice == "add":
addEntry()
elif choice == "no":
createAddBook()
print("Address book has been created!")
choice = input("Would you like to add an entry to the address book? (yes/no)" + "\n")
if choice == "yes":
addEntry()
elif choice == "no":
inuse = False
elif choice == "close":
break
I understand that you want to create your address book as a CSV file (store one entry per line, and use commas to separate the fields of a given entry). Is that your goal? To manage such a file, the easiest solution is to use the csv module from the standard Python library. Here is a link to the documentation page:
https://docs.python.org/3/library/csv.html#examples

Need help placing info on a new line in a file

im trying to create a database by using dictionaries. i convert the dictionary into a string once ive finished adding and deleting things from it but when i want to save the string, i would like the the keys to be on a new line from each other.
here is my code so far:
print('|-----Welcome to the Address Book-------|')
print('|----------------------------------------|')
print('|Please choice from the following:-------|')
print('|----------1: Find Contact------------|')
print('|----------2: Add Contact------------|')
print('|----------3: Delete Contact------------|')
print('|----------4: Quit Address Book----------|')
choice = [1, 2, 3, 4, 5]
document = open('addresses.txt', 'r+')
address = {}
for line in document:
if line.strip():
key, value = line.split(None, 1)
address[key] = value.split()
document.close()
open('addresses.txt', 'w')
while 1:
answer = 0
while answer not in choice:
try:
answer = int(input("Enter here: "))
except ValueError:
0
if answer == 1:
x = input('Enter his/her name: ')
if x in address:
print("This is their address: ", address[x])
else:
print('Contact does not exist!')
if answer == 2:
x = (input('Enter new contact: '))
x = x.replace(" ", "_")
if x in address:
while True:
z = str(input('Contact '+x+' with address: '+str(address[x]) + ' already existed, do you want to override?(Yes/No)'))
if z == 'yes':
b = input('Enter Address: ')
c = input('Enter postcode: ')
del address[x]
break
elif z == 'no':
break
else:
print('Please choose yes or no')
else:
b = input('Enter Address: ')
c = input('Enter postcode: ')
b = b.replace(" ", "_")
c = c.replace(" ", "_")
address[x] = b, c
if answer == 3:
z = input('Enter whom you would like to delete: ')
if z in address:
del address[z]
else:
print('Contact does not exist!')
if answer == 4:
a = "{}':(),[]"
ok = str(address)
for char in a:
ok = ok.replace(char, "")
document = open('addresses.txt', 'r+')
document.write(ok + '\n')
document.close()
break
when saving to file, i would like to save each key and its info like this:
>Bob address postcode
>Sam address postcode
but instead it is saved like this:
>Bob address postcode Sam address postcode
When writing a dictionary to file, do the following:
with open('/file/path', 'w') as f:
for k, v in d.items():
f.write(k + v + "\n")
This assumes a few things:
You want to overwrite the file, not append; if you do, switch 'w' to 'a'
All the key and value items are str
I don't like using 'r+'. You should open(filename, "r") when you want to read from a file and open(filename, "w") when you want to read your file. In my opinion, it's way easier because while using 'r+', you have to think about where the seek is (the blinking cursor that you see while writing/editing somewhere).
For that you'll need something like:
file=open(filename,"r+")
file.seek(0)
file.write("something" + "\n")
Well, I don't really use the "r+" method very much so I can't explain anymore. I suggest that you read more about it in the docs.
If you print str(address) to your screen, you will understand why this happens. The str command converts everything (i.e. keys and values) to a concatanated string and that will be stored in your document file.
Instead you should save the items of your address book one by one, iterating over all persons.
ok = ""
for person in address:
ok += person + " " + address[person] + "\n"
with open('addresses.txt', 'w') as file_out:
file_out.write(ok)

How to write in new line in a file?

I need to create a program that saves people's information e.g. their name in a text file depending on the first letter of their surname so if their surname starts with a K it goes into MyFile1.
I need it to loop like I have done because it's an unknown number of people however I want each person to be written in a different line in the text file is there a way to do this.
The code at the bottom puts each separate information into a new line and I don't want that I want each different person to be in a new line.
MyFile1 = open("AL.txt", "wt")
MyFile2 = open("MZ.txt", "wt")
myListAL = ([])
myListMZ = ([])
while 1:
SurName = input("Enter your surname name.")
if SurName[0] in ("A","B","C","D","E","F","G","H","I","J","K","L"):
Title = input("Enter your title.")
myListAL.append(Title);
FirstName = input("Enter your first name.")
myListAL.append(FirstName);
myListAL.append(SurName);
Birthday = input("Enter birthdate in mm/dd/yyyy format:")
myListAL.append(Birthday);
Email = input("Enter your email.")
myListAL.append(Email);
PhoneNumber = input("Enter your phone number.")
myListAL.append(PhoneNumber);
for item in myListAL:
MyFile1.write(item+"\n")
elif SurName[0] in ("M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"):
Title = input("Enter your title.")
myListMZ.insert(Title);
FirstName = input("Enter your first name.")
myListMZ.append(FirstName);
myListMZ.append(SurName);
Birthday = input("Enter birthdate in mm/dd/yyyy format:")
myListMZ.append(Birthday);
Email = input("Enter your email.")
myListMZ.append(Email);
PhoneNumber = input("Enter your phone number.")
myListMZ.append(PhoneNumber);
line.write("\n")
for item in myListMZ:
MyFile2.write(line)
elif SurName == "1":
break
MyFile1.close()
MyFile2.close()
You are looking for join.
When you have a list of items you can join them in a single string with.
l = ['a', 'b', 'c']
print(''.join(l))
produces
abc
You can not only use the empty string but also another string which will be used as separator
l = ['a', 'b', 'c']
print(', '.join(l))
which now produces
a, b, c
In your examples (for example the first write)
MyFile1.write(','.join(MyListAL) + '\n')
If you happen to have something in the list which is not a string:
MyFile1.write(','.join(str(x) for x in MyListAL) + '\n')
(you can also use map, but a generator expression suffices)
Edit: adding the map:
MyFile1.write(','.join(map(str, MyListAL)) + '\n')
In your case I would rather use a list of dictionaries, where a person with all its infos is a dictionary. Then you can convert it to a JSON string, which is a standard format for representing data. (Otherwise you need to define your own format, with delimiters between the items.)
So something like this:
import json # at the top of your script
# I would create a function to get the information from a person:
def get_person_input():
person = {}
person["surname"] = input("Surname: ")
person["title"] = input("Title: ")
person["email"] = input("Email: ")
# TODO: do whatever you still want
return person
# Later in the script when you want to write it to a file:
new_line = json.dumps( person )
myfile.write( new_line + "\n" )
Parsing a json is also very easy after all:
person = json.loads(current_line) # you can handle exception if you want to make sure, that it is a JSON format
You can use in your code for the decision in which array it should be written something like this:
SurName = input("Enter your surname name.")
if SurName[0] <= 'L':
...
else:
...
This will make your script more clear and robust.

How to convert JSON (Twitter Data) to CSV using Python

I am attempting to query the twitter search engine (search.twitter.com), convert the results into json, and then prepare the results as a csv for a research project. I am a python novice, but I have managed to code 2/3 of the program myself. However, I have a difficult time converting my json file into the csv format. I have tried various suggested techniques without success. What am I doing wrong here?
Here is what I have so far:
import twitter, os, json, csv
qname = raw_input("Please enter the term(s) you wish to search for: ")
date = int(raw_input("Please enter today's date (no dashes or spaces): "))
nname = raw_input("Please enter a nickname for this query (no spaces): ")
q1 = raw_input("Would you like to set a custom directory? Enter Yes or No: ")
if q1 == 'No' or 'no' or 'n' or 'N':
dirname = 'C:\Users\isaac\Desktop\TPOP'
elif q1 == 'Yes' or 'yes' or 'y' or 'Y':
dirname = raw_input("Please enter the directory path:")
ready = raw_input("Are you ready to begin? Enter Yes or No: ")
while ready == 'Yes' or 'yes' or 'y' or 'Y':
twitter_search = twitter.Twitter(domain = "search.Twitter.com")
search_results = []
for page in range (1,10):
search_results.append(twitter_search.search(q=qname, rpp=1, page=page))
ready1 = raw_input("Done! Are you ready to continue? Enter Yes or No: ")
if ready1 == 'Yes' or 'yes' or 'y' or 'Y':
break
ready3 = raw_input("Do you want to save output as a file? Enter Yes or No: ")
while ready3 == 'Yes' or 'yes' or 'y' or 'Y':
os.chdir(dirname)
filename = 'results.%s.%06d.json' %(nname,date)
t = open (filename, 'wb+')
s = json.dumps(search_results, sort_keys=True, indent=2)
print >> t,s
t.close()
ready4 = raw_input("Done! Are you ready to continue? Enter Yes or No: ")
if ready4 == 'Yes' or 'yes' or 'y' or 'Y':
break
ready5 = raw_input("Do you want to save output as a csv/excel file? Enter Yes or No: ")
while ready5 == 'Yes' or 'yes' or 'y' or 'Y':
filename2 = 'results.%s.%06d.csv' %(nname,date)
z = json.dumps(search_results, sort_keys=True, indent=2)
x=json.loads(z)
json_string = z
json_array = x
columns = set()
for entity in json_array:
if entity == "created_at" or "from_user" or "from_user_id" or "from_user_name" or "geo" or "id" or "id_str" or "iso_language_code" or "text":
columns.update(set(entity))
writer = csv.writer(open(filename2, 'wb+'))
writer.writerow(list(columns))
for entity in json_array:
row = []
for c in columns:
if c in entity: row.append(str(entity[c]))
else: row.append('')
You have several different problems going on.
First off, the syntax of
x == 'a' or 'b' or 'c'
probably doesn't do what you think it does. You should use
x in ('a', 'b', 'c')
instead.
Second, your ready5 variable never changes and won't work right in the loop. Try
while True:
ready5 = raw_input("Do you want to save output as a csv/excel file? Enter Yes or No: ")
if ready5 not in (...):
break
And finally, there's something wrong with your dumping/loading code. What you're getting from twitter should be a JSON string. There's some code you've left out from your question, so I can't tell for sure, but I don't think you want to be using json.dumps at all. You're reading from JSON (using json.loads) and writing to CSV (using csv.writer.writerow).
A different approach would be to have tablib do the actual conversion for you:
import tablib
data = tablib.Dataset()
data.json = search_results
filename = 'results.%s.%06d.csv' %(nname,date)
csv_file = open(filename, 'wb')
csv_file.write(data.csv)
After some searching around, I found the answer here: http://michelleminkoff.com/2011/02/01/making-the-structured-usable-transform-json-into-a-csv/
The code should look something like this:(if you are search the twitter python api)
filename2 = '/path/to/my/file.csv'
writer = csv.writer(open(filename2, 'w'))
z = json.dumps(search_results, sort_keys=True, indent=2)
parsed_json=json.loads(z)
#X needs to be the number of page you pulled less one. So 5 pages would be 4.
while n<X:
for tweet in parsed_json[n]['results']:
row = []
row.append(str(tweet['from_user'].encode('utf-8')))
row.append(str(tweet['created_at'].encode('utf-8')))
row.append(str(tweet['text'].encode('utf-8')))
writer.writerow(row)
n = n +1
Thanks Everyone for the help!

Categories

Resources