How to write in new line in a file? - python

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.

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 make data entered by user to appear below headers

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!

I am trying to create an address book program that will append user input to its appropriate list

I am having trouble getting past writing user input to my list what am I doing wrong here? This is an address book program that I am writing, the assignment is to create parallel lists that will store user input data in the appropriate list using a for or while loop. The program must also have a search function which you can see is at the bottom of the code. My issue that I am having is getting the program to store data within my lists. Unfortunately lists are something that give me lots of trouble I just cant seem to wrap my head around it no matter how much research I have done. The issue im running into is the append.data function when trying to write lastname and firstname to my list of names. what am I doing wrong?
#NICHOLAS SHAFFER
#5/11/2016
#MYADDRESSBOOK
def menu():
index = 0
size = 100
count = 0
answer = raw_input("Are You Creating An Entry [Press 1] \nOr Are You Searching An Entry [Press 2] ")
if answer == "1" :
print ("This is where we create")
append_data(index, size, count)
elif answer == "2" :
print ("this is where we search")
search_database()
name[size]
phone[size]
addresss[size]
# IF we are creating
def append_data(index, size, count):
# collect information
for index in range(0, 100):
optOut = 'no'
while optOut == 'no':
lastname[count] = raw_input("What is the persons last name? ")
firstname[count] = raw_input("What is the persons first name? ")
phone[count] = raw_input("What id the persons phone number? ")
address[count] = raw_input("What is the persons address? ")
count = count + 1
print 'Would you like to create another entry?'
optOut = raw_input('Would you like to create another entry? [ENTER YES OR NO]:')
if optOut == 'yes':
menu()
#create string to print to file
#print temp1
#print (firstname + " " + lastname + ", " + phone + ", " + email + ", " + address)
print listName[index]
print listPhone[index]
print listAddress[index]
print 'file has been added to your addressbook sucessfuly'
menu()
# SEARCHING FOR A RECORD
def search_database():
searchcriteria = raw_input("Enter your search Criteria, name? phone, or address etc ")
print searchcriteria
if searchcriteria == "name":
temp1 = open(listName[lastname, firstname],"r")
print temp1
if searchcriteria == "phone":
temp1 = open(listPhone[0], "r")
print temp1
if searchcriteria == "address":
temp1 = open(listAddress[0], "r")
print temp1
else:
print "sorry you must enter a valid responce, try again."
menu()
for line in temp1:
if searchcriteria in line:
print line
errorMessage()
# USER DID NOT PICK CREATE OR SEARCH
def errorMessage():
print ("Incorrect Answer")
exit()
menu()
Your error message says it all:
line 34, in append_data lastname[count]... NameError: global name 'lastname' is not defined
You'll get this same error if you type lastname[4] in any interpreter -- you've simply never defined a list called lastname, so you can't access items in it. In the short term, you can fix this with a line
lastname = list()
You're going to end up with more troubles though; lastname won't be accessible outside the function where you define it, neither will listName. I'd probably approach that by writing them into a data file/database, or maybe creating a quick class whose members will all have access to self.lastname.
My final append for lists thanks again Noumenon
def append_data(index, size, count):
lastnames = list()
if count < size -1:
lastname = raw_input("What is the persons last name? ")
lastnames.append(lastname)
print lastnames
firstnames = list()
if count < size - 1:
firstname = raw_input("What is the persons first name? ")
firstnames.append(firstname)
print firstnames
phones = list()
if count < size - 1:
phone = raw_input("What id the persons phone number? ")
phones.append(phone)
print phones
addresss = list()
if count < size - 1:
address = raw_input("What is the persons address? ")
addresss.append(address)
print addresss
listName = (lastnames, firstnames)
addressbook =(listName, phones, addresss)
index = index + 1
count = count + 1
print addressbook
optOut = raw_input('Would you like to create another entry? [Enter YES or NO]: ')
if optOut == 'YES':
menu()
print 'file has been added to your addressbook sucessfuly'
menu()

Is there any way to enter a "while" loop while a boolean value is false

I'm basically running a code that builds up an address book into a text file through user entries.
While doing so, I'm checking to see if the inputed information is correct and, in the case that it's not, asking them to correct it. However, I realize that it's possible (though unlikely) that a user could input incorrect information an indefinite number of times and so I'm looking to implement a "while" loop to work around this.
In the case of the code below, I'm basically attempting to have it so that instead of the first ifelse entry I can enter into a loop by checking for the boolean value of "First_Name.isalpha():". However, I can't really think of a way to enter into it as when "First_Name.isalpha():" is true I don't need to enter into the loop as the entry is correct. When it's false, we skip over the loop altogether without having the entry corrected.
That basically prompts the question of whether or not there is a way to enter into a loop for when a boolean value is false. Or, if there's another creative solution that I'm not considering.
Thanks,
A Novice Coder
NewContact = "New Contact"
def NewEntry(NewContact):
# Obtain the contact's information:
First_Name = input("Please enter your first name: ")
Last_Name = input("Please enter your last name: ")
Address = input("Please enter your street address: ")
City = input("Please enter your city of residence: ")
State = input("Please enter the 2 letter abbreviation of your state of residence: ")
ZipCode = input("Please enter your zip code: ")
Phone_Number = str(input("Please enter your phone number: "))
# Ensure all information inputted is correct:
if First_Name.isalpha():
First_Name = First_Name.strip()
First_Name = First_Name.lower()
First_Name = First_Name.title()
else:
First_Name = input("Please reenter your first name. Be sure to to include letters exclusively: ")
if Last_Name.isalpha():
Last_Name = Last_Name.strip()
Last_Name = Last_Name.lower()
Last_Name = Last_Name.title()
else:
Last_Name = input("Please reenter your first name. Be sure to to include letters exclusively: ")
# Organize inputted information:
NewContact = Last_Name + ", " + First_Name
FullAddress = Address + " " + City + ", " + State + " " + ZipCode
# Return information to writer to ensure correctness of information
# Write information onto document
TheFile = open("AddressBook", "w")
TheFile.write(str(NewContact) + "\n")
TheFile.write(str(FullAddress) + "\n")
TheFile.write(str(Phone_Number) + "\n")
TheFile.close()
NewEntry(NewContact)
You're looking for the not operator, which inverts a boolean value:
>>> not False
True
>>> not True
False
>>> not "".isalpha()
True
>>> not "abc".isalpha()
False
You can tack it on the front of any expression that's a valid condition for an if or while.
Use this structure
invalid = True
while invalid:
## get inputs
## validate inputs
## set invalid accordingly

perform different splits based off different criteria to create a distinct output

When I execute the below python code I have written, (I am trying to create a user name based off three distinct scenarios (1.user enters First, middle, and last name, 2. user enters first and last name, 3. user enters only last name. I am attempting to create a username based off the first 4 characters of the last name+first initial (when provided)+middle initial(when provided). When I execute the below code, using the first+last name combination or just last name, I receive
lastName = (listnames[2])
IndexError: list index out of range
def entirename(fullName):
lowername = str.lower(fullName)
delimiter =' '
listnames = (lowername.split(delimiter))
lastName = (listnames[2])
lname = lastName[0:4]
fInit = listnames[0]
fname = fInit[0]
mInit = listnames [1]
mname = mInit[0]
username =lname+fname+mname
return
def firstlast(fullName):
lowername = str.lower(fullName)
delimiter =' '
listnames = (lowername.split(delimiter))
lstName = (listnames[1])
lname = lastName[0:4]
fInit = listnames[0]
fname = fInit[0]
username = lname+fname
return
def last(fullName):
lowername = str.lower(fullName)
delimiter =' '
listnames = (lowername.split(delimiter))
lstName2 = (listnames[0])
lname = lstName2[0:4]
username = lname
return
def main():
print "Hello! This program will contruct a new userid for you."
print ""
fullName = raw_input('Please enter your full name: ')
while True:
if fullName[2]:
entirename(fullName)
break
elif fullname[1]:
firstlast(fullName)
break
elif fullname[0]:
last(fullName)
break
main()
Or you could write something simpler like:
def get_id():
print "Hello! This program will contruct a new userid for you.\n"
name = raw_input('Please enter your full name: ').lower().split(' ')
userid = name[-1][:4] # first 4 chars of last name
if len(name) > 1:
userid += name[0][0] # first char of opt first name
if len(name) > 2:
userid += name[1][0] # first char of opt middle name
return userid
userid = get_id()
print 'userid:', userid
I think your main() is wrong. ... fullname[2] is the third character of the string... if I am not mistaken...? Since it's not split yet.
EDIT:
So split() it in main() and you should be good to go.
Also notable that you can't str.lower() a list. Which is what tipped me off.
RE-EDIT:
This should do the trick. Fully tested rewrite:
def main():
print "Hello! This program will contruct a new userid for you.\n"
fullstring = raw_input('Please enter your full name: ')
fullName = fullstring.split(' ')
lowerName = list()
for each in fullName :
lowerName.append(each.lower())
lowerName.reverse()
lastname = lowerName.pop(0)[0:4]
lowerName.reverse()
if lowerName : lastname += lowerName.pop(0)[0]
if lowerName : lastname += lowerName.pop(0)[0]
return lastname
main()

Categories

Resources