Save input as text file in python - python

I got a simple python code with some inputs where a user has to type name, age, player name and his best game.
Now I want that all these inputs from the user were saved as a text file or something like this.
I tried
with open ("Test_", "a") as file:
User_input = file.write(input("here type in your name"))
I tried it with with open ... n where I create a new text file before which I open in python and add something. But everything I tried failed. Hope my English is good enough to understand what kind of problem I have.

import csv
OUTFILE = 'gameplayers.csv'
def main():
player = []
morePlayer = 'y'
while morePlayer == 'y':
name = input('Enter your name: ')
age = input('Your age: ')
playerName = input('Your player name: ')
bestGame = input('What is your best game: ')
player.append([name, age, playerName, bestGame])
morePlayer = input('Enter information of more players: (y, n): ')
with open(OUTFILE, 'a', encoding='utf_8') as f:
csvWriter = csv.writer(f, delimiter=',')
csvWriter.writerows(player)
if __name__ == '__main__':
main()

If you want to keep adding new data, use a otherwise, use w to overwrite. I've used a in this example:
name = input('Name: ')
age = input('Age: ')
best_game = input('Best Game: ')
with open('user_data.txt', 'a') as file:
file.write(f'Name: {name} - Age: {age} - Best Game: {best_game}\n')

First of all, you need to know the difference between 'a' and 'w' in with open. 'w' stands for write, meaning every time you call it, it will be overwritten. 'a' stands for append, meaning new information will be appended to the file. In your case, I would have written the code something like this
userInput = input(“Enter your name: “)
with open(“filename.txt”, “a”) as f:
f.write(userInput)
If you instead want to overwrite every time - change the 'a' to a 'w'.

Related

How to not duplicate elements when entering array in csv

I have a piece of code used to enter student information. But I want to transform it so that Admission no. cannot be repeated, when entering an existing number, a message will be printed if you want to re-enter an existing number. below is my code
import csv
student_fields = ['Admission no.','Name','Age','Email','Phone']
student_database = 'students.csv'
def add_student():
print("-------------------------")
print("Add Student Information")
print("-------------------------")
global student_fields
global student_database
student_data = []
for field in student_fields:
print(field)
value = input("Enter " + field + ": ")
student_data.append(value)
with open(student_database,"a",encoding = "utf-8") as f:
writer = csv.writer(f)
writer.writerows([student_data])
print("Data saved successfully")
input("Press any key to continue")
return
You can do something like this. As Barmar suggested, put the admission numbers in a set at the start of your definition. Then, check the user's input against those numbers. Create a while loop that doesn't let the user input any other value until they enter a new Admission no (and tell them that they are entering a duplicate admission number). Once everything looks good, write it to the csv.
import csv
student_fields = ['Admission no.','Name','Age','Email','Phone']
student_database = 'students.csv'
def add_student():
print("-------------------------")
print("Add Student Information")
print("-------------------------")
global student_fields
global student_database
# create a set of the already entered admission numbers
with open('students.csv', 'r') as file:
reader = csv.reader(file)
admissionNums = {x[0] for x in reader if x}
student_data = []
for field in student_fields:
print(field)
value = input("Enter " + field + ": ")
# while the user is entering the admission no. field and they are entering a duplicate, keep prompting them for a new/unique number
while field == 'Admission no.' and value in admissionNums:
print("Admission no. already in file, try again")
value = input("Enter " + field + ": ")
student_data.append(value)
# I also added `newline=''` so that it would stop creating an empty row when writing to the file
# You can remove this if you want to keep making a new row every time you write to it
with open(student_database,"a",encoding = "utf-8", newline='') as f:
writer = csv.writer(f)
writer.writerows([student_data])
print("Data saved successfully")
input("Press any key to continue")
# The return statement here is not necessary

How to delete given element from a python dictionary?

I am practicing python and doing an exercise where I have to ask for input of different information from patients of a hospital (name, last name, etc) this information has to be saved in a different json file. I managed to do it however I also have to make it so, with an input, I can remove/edit a specific patient from the dictionary (along with all of their info) while keeping the others intact.
I was thinking that maybe I could assign a number to every patient that's added, so this patient can be tracked with the number, however I'm not sure how to code that. I did however made a function to clear everything from the json file, but it has to remove/edit someone specific, not everyone.
My code so far is:
import json
def read_file(file_name):
obj_arch = open(file_name, 'rt', encoding='utf-8')
str_contenido = obj_arch.read()
res = json.loads(str_contenido)
obj_arch.close()
return res
def save_file(file_name, lista):
obj_arch = open(file_name, 'wt', encoding='utf-8')
str_content_to_save = json.dumps(lista)
print(str_content_to_save)
obj_arch.write(str_content_to_save)
obj_arch.close()
opcion = int(input("choose an option: 1 - read. 2 - save"))
if opcion == 1:
lista = read_file('prueba_json.json')
print("Full list:")
print(lista)
else:
lista = read_file('prueba_json.json')
while True:
print("--- PATIENT INFO ---")
Name = input("Input name: ")
Lastname = input("Input lastname: ")
DateB= input("Input date of birht: ")
repeat = input("Do you want to add more info?: ")
clean_file = input("Clean everything from the json file? (yes/no): ")
lista.append({
"Name": Name,
"Lastname": Lastname,
"Date of Birth": DateB
})
if repeat == 'no' or repeat == 'NO':
break
save_file('prueba_json.json',lista)
With this I was able to sabe the patients info in the json file, but how can I write another input like "Insert number of patient to remove or delete" to do that?
In order to clean the whole json file I've done it with this:
def clean_json():
with open('prueba_json.json', 'w') as arc:
arc.writelines(["[{}]"])
if clean_file == "yes" or clean_file == "YES":
clean_json()
Maybe I could adapt some of this to remove or delete someone instead of the whole file?

How do i change this so when i run the functions it adds to my .txt file?

Im supposed to make a function for adding name and number to a.txt file, and one for reading the file. What am I doing wrong and how do I correct it? first post so I dont know if something is in the wrong format, sorry.
def add():
while True:
name = input("Name and number: ")
with open("Telefon.txt", "a") as f:
f.write(name)
f.close()
if name == "Enter":
break
def read():
f = open("Telefon.txt", "r")
print(f.read)
There are certain logical and optimizations mistake in your code you should not open file again and again and close it in loop, also use empty condition to terminate the loop e.g. press enter without entering any thing. For reading, I replaced your read method with redlines method
def add():
with open("Telefon.txt", "a") as f:
while True:
name = input("Name and number: ")
f.write(name + '\n')
if name == "":
break
def read():
f = open("Telefon.txt", "r")
print("".join(f.readlines()))
add()
read()
The output is following

Python only printing last data entered

I have an assignment to create a class that holds the name of an employee, id number, department, and job title. The user should be able to input the information for multiple employees and have all of the information printed out at the end.
The problem I am facing is that only the last employee's information is being printed out.
import pickle
import employee
data = 'data.dat'
def main():
output_file = open(data, 'wb')
end_of_file = False
keep_going = 'Y'
while keep_going == 'Y':
name = str(input('Name of employee: '))
ID_num = int(input('Employee ID number: '))
dep = str(input('Department: '))
job = str(input('Job Title: '))
emp = employee.Employee(name, ID_num)
emp.set_department(dep)
emp.set_job_title(job)
pickle.dump(emp, output_file)
keep_going = input('Enter another employee file? (Use Y / N): ')
input_file = open(data, 'rb')
while not end_of_file:
try:
emp = pickle.load(input_file)
display_data(emp)
except EOFError:
end_of_file = True
input_file.close()
if keep_going == 'N':
print(display_data(emp))
output_file.close()
def display_data(emp):
print('Name','\t','\t','ID Number','\t','Department','\t','\t','Job Title')
print(emp.get_name(), '\t', emp.get_ID_num(),'\t','\t',emp.get_department(),'\t','\t',emp.get_job_title())
main()
If anyone knows why this is happening and has any suggestions on how to fix it I would really appreciate it as I am new to python and don't fully understand all of the concepts
You need to store the employees in memory and then write to the file in the end. Also, I don't understand why you need this bit of code, it doesn't seem to be doing anything :
input_file = open(data, 'rb')
while not end_of_file:
try:
emp = pickle.load(input_file)
display_data(emp)
except EOFError:
end_of_file = True
input_file.close()
So we remove this, and make some other modifications. Your modified code :
import pickle
import employee
data = 'data.dat'
def display_data(emp):
print('Name','\t','\t','ID Number','\t','Department','\t','\t','Job Title')
print(emp.get_name(), '\t', emp.get_ID_num(),'\t','\t',emp.get_department(),'\t','\t',emp.get_job_title())
def main():
output_file = open(data, 'wb')
emp_list = []
keep_going = 'Y'
while keep_going == 'Y':
name = str(input('Name of employee: '))
ID_num = int(input('Employee ID number: '))
dep = str(input('Department: '))
job = str(input('Job Title: '))
emp = employee.Employee(name, ID_num)
emp.set_department(dep)
emp.set_job_title(job)
emp_list.append(emp)
keep_going = input('Enter another employee file? (Use Y / N): ')
pickle.dump(emp_list, output_file)
output_file.close()
if keep_going == 'N':
input_file = open(data, 'rb')
employees = pickle.load(open(data, "rb"))
for emp in employees:
print(display_data(emp))
main()
Also, the printing can be made cleaner :
from tabulate import tabulate
def display_data(employees):
infos = []
for emp in employees:
infos.append([emp.get_name(), emp.get_ID_num(), emp.get_department(), emp.get_job_title()])
print(tabulate(infos, headers=["Name", "ID num", "Department", "Job Title"], tablefmt="fancy_grid"))
So, to print, replace
for emp in employees:
print(display_data(emp))
with
display_data(employees)
HTH.
Every time pickle.dump() is called, it overwrites the existing file. So firstly you need to store all the employees in a list and then write it to file using dump().
While retrieving also you need to load data from file using pickle.load() into a list.

How to write to a text file using iteration?

My code does not write to a file, what am I doing wrong? I am trying to program to continue to ask for products until the user does not enter a product code. I want all products to be saved in the file.
store_file = open("Database.txt", "w")
NewProduct = ""
while NewProduct != False:
contine = input("Press 1 to enter a new product press 2 to leave: ")
if contine == "1":
print("Enter your product information")
information = []
product = input("What's the product code: ")
information.append(product)
description = input("Give a description of the product: ")
information.append(description)
price = input("Enter price of product: ")
information.append(price)
information = str(information)
clean = information.replace("]","").replace("[","").replace(",","").replace("'","")
store_file.write(clean)
elif contine == "2":
NewProduct = False
else:
print("Your input is invalid")
store_file.close
I got the program working with the following adjustments. See comments for explanations:
store_file = open("Database.txt", "w")
NewProduct = ""
while NewProduct != False:
continue = raw_input("Press 1 to enter a new product press 2 to leave: ")
#Changed to raw_input because input was reading in an integer for 1 rather than a
#string like you have set up. This could be specific to my IDE
if continue == "1":
print("Enter your product information")
information = []
product = raw_input("What's the product code: ")
information.append(product)
description = raw_input("Give a description of the product: ")
information.append(description)
price = raw_input("Enter price of product: ")
information.append(price)
information = str(information)
clean = information.replace("]","").replace("[","").replace(",","").replace("'","")
store_file.write(clean + "\n")
#Added a line break at the end of each file write
elif contine == "2":
NewProduct = False
else:
print("Your input is invalid")
store_file.close() #Added parentheses to call the close function
I'm assuming the problem here is that you're using Python 2, and input isn't doing what you think it does. In Python 2, input evals the input as if it were Python source code, so if someone enters 2, it's going to return the int value 2, not "2". In Python 2, you want to use raw_input, always (eval-ing random user input not being secure/reliable).
Also, while on CPython (the reference interpreter) files tend to naturally close themselves when they go out of scope, you made an effort to close, but forgot to actually call the close method; store_file.close looks up the method without calling it, store_file.close() would actually close it. Of course, explicit close is usually the wrong approach; you should use a with statement to avoid the possibility of forgetting to close (or of an exception skipping the close). You can replace:
store_file = open("Database.txt", "w")
...
store_file.close()
with:
with open("Database.txt", "w") as store_file:
... do all your work that writes to the file indented within the with block ...
... When you dedent from the with block, the file is guaranteed to be closed ...
There are other issues though. What you're doing with:
information = str(information)
information = information.replace("]","").replace("[","").replace(",","").replace("'","")
is terrible. I'm 99% sure what you really wanted was to just join the inputs with spaces. If you switch all your input calls to raw_input (only on Python 2, on Python 3, input is like raw_input on Python 2), then your list is a list of str, and you can just join them together instead of trying to stringify the list itself, then remove all the list-y bits. You can replace both lines above with just:
information = ' '.join(information)

Categories