Why isn't my file writing method working? - python

import os
books = open(os.path.expanduser("~/Desktop/books.txt")).read()
b= books.split('\n')
del b[-1]
book={}
for i in b:
b1=i.split('\t')
book[b1[0]]=[b1[1],b1[2],b1[3]]
def all_book():
print "The Book List"
books = open(os.path.expanduser("~/Desktop/books.txt"))
print books.read()
def add_book():
print "Registering New Book"
books = open(os.path.expanduser("~/Desktop/books.txt"))
name = raw_input("Title: ")
author= raw_input("Author Name: ")
publisher =raw_input("Publisher: ")
n= int(b1[0])
n1 = n+1
newb= [str(n1), '\t', name, '\t', author,'\t', publisher]
books.writelines(newb) #Adding file to the list
newb = {}
newb[n1]=[name, author, publisher]
print 'A New Book Added!'
return newb
def del_book():
print "Deleting Books"
delnum = str(raw_input("Registered Number:"))
if delnum in book:
del book[delnum]
else:
print delnum, "Not Found"
def show_menu():
print '''
1) add new
2) all show
3) delete
4) search
5) Save/out
'''
menu_choice = raw_input('what --> ')
if menu_choice == '1':
add_book()
elif menu_choice == '2':
all_book()
elif menu_choice == '3':
del_book()
show_menu()

books = open(os.path.expanduser("~/Desktop/books.txt")).read()
Your error lies here. If you do not specify a file opening mode, Python will default to 'read' mode, meaning you cannot write to it.
The correct syntax for opening a file for writing is:
books = open('file', 'w')
This page has a table of file access modes down the page.

open() default open the file as read, and that's why you can't write your new book into the text file.

Related

How to save the data gathered in the address book?

I am using a file in text edit ubuntu. I am trying to figure out a way to save it. When I close the python shell and rerun it, it deletes all past info. Would I have to make a new function?
AdressBook = '/home/bookworm/AdressBook.txt'
contacts = {}
def write():
Data = open(AdressBook,'w')
for name, many in contacts.items():
Data.write(name + ',' + many)
Data.close()
def read():
Data = open(AdressBook, 'r')
stuff = Data.read()
print(stuff)
Data.close()
user = input('Would you like to acess your adress book?')
if user == 'yes' or 'yep' or 'y' or 'Yes' or 'YES!' or 'YES' or 'Yurp' or 'Yeppers' or
'si'or'1':
It is only the deleted and added contacts to be saved
while user != 5:
user = input('''Select One:
Press 1 to update
Press 2 to display all contacts
Press 3 to search adress book
Press 4 to delete contacts
Press 5 to quit your adress book.''')
if user == '1':
name = input('Please enter the name of the contact that you would like to add.')
contact = input('Please enter the contact information of %s.'%name)
Name = '\n' + name
contacts.update( {Name : contact} )
print('')
print('%s was added to your adress book!' %name)
print('')
write()
elif user == '2':
read()
To call read function
elif user == '3':
name = input('What is the name of the person whose contacts you need?')
print(contacts[name])
To delete a contact
elif user == '4':
name = input('Type in the name of the contact that you would like to delete.')
del contacts[name]
print('Your contact List has sucessfully deleted %s' %name)
write()
elif user == '5':
print('Thank you for acessing your adress book!')
exit()
else:
exit()
Your file becomes empty everytime because you are taking contacts = {} in the start of the program. So instead of creating an empty dictionary, you need to initialize the dictionary with the file contents in the starting.
AdressBook = '/home/bookworm/AdressBook.txt'
contacts = initialize_contacts()
def write():
Data = open(AdressBook,'w')
for name, many in contacts.items():
Data.write(name + ',' + many + '\n')
Data.close()
def read():
Data = open(AdressBook, 'r')
stuff = Data.read()
print(stuff)
Data.close()
return stuff
def initialize_contacts():
data = read()
contact_list = data.split('\n')
for contact in contact_list[:-1]:
name,cont = contact.split(',')
contacts[name] = cont

No attribute present

I am quite new to python and I am getting an attribute error.
import FileHandeling as fh;
import os;
CounterFilePath = os.path.dirname(os.path.realpath(__file__))+"/counter.txt";
FilePath = os.path.dirname(os.path.realpath(__file__))+"/FileIO.txt";
class Employee:
def createEmployee(self):
numOfEmployees = int(input("Enter number of employees: "));
empDetails = [];
for i in range(numOfEmployees):
empFName, empLName, empSalary, empEmailId = raw_input("Enter employee first name: "), raw_input("Enter employee last name: "), raw_input("Enter employee salary: "), raw_input("Enter employee Email ID: ");
string = str(i)+" "+empFName+" "+empLName+" "+empSalary+" "+empEmailId+"\n";
empDetails.append(string);
with open(FilePath,"a+") as fo:
fo.seek(0);
fh.createFile(fo,numOfEmployees,empDetails,CounterFilePath);
def searchEmployee(self):
choice = int(input("Press:\n1 to search by First Name\n2 to search by Last Name\n3 to search by Salary\n4 to search by Email ID\n"));
print "Enter the",;
if(choice == 1):
print "First Name:",;
elif(choice == 2):
print "Last Name:",;
elif(choice == 3):
print "Salary:",;
elif(choice == 4):
print "Email ID:",;
searchStr = raw_input();
with open(FilePath,"r") as fo:
string = fh.readFile(fo,searchStr,choice-1);
while line in string:
print line;
def updateEmployee(self):
print "Leave the entries empty if you dont want to update that entry.";
lineNum = input("Enter the line number of the entry you want to update: ");
with open(FilePath,"r") as fo:
empFName, empLName, empSalary, empEmailId = raw_input("Enter employee first name: "), raw_input("Enter employee last name: "), raw_input("Enter employee salary: "), raw_input("Enter employee Email ID: ");
if(empFName == ""):
record = fh.readFile(fo,lineNum-1,0);
empDetails = record[0].split();
empFName = empDetails[1];
if(empLName == ""):
record = fh.readFile(fo,lineNum-1,0);
empDetails = record[0].split();
empLName = empDetails[2];
if(empSalary == ""):
record = fh.readFile(fo,lineNum-1,0);
empDetails = record[0].split();
empSalary = empDetails[3];
if(empEmailId == ""):
record = fh.readFile(fo,lineNum-1,0);
empDetails = record[0].split();
empEmailId = empDetails[4];
updateStr = str(lineNum-1)+" "+empFName+" "+empLName+" "+empSalary+" "+empEmailId+"\n";
fh.updateRecord(fo,FilePath,updateStr,lineNum-1);
def deleteEmployee(self):
lineNum = input("Enter the line number of the entry you want to delete: ");
with open(FilePath,"r") as fo:
fh.deleteRecord(fo,FilePath,lineNum-1);
def main(self):
goOn = True;
employee = Employee();
while goOn:
choice = input("Press:\n1 to enter a new employee\n2 to search employee\n3 to update employee\n4 to delete employee\n0 to exit\n");
if(choice == 1):
employee.createEmployee();
elif(choice == 2):
employee.searchEmployee();
elif(choice == 3):
employee.updateEmployee();
elif(choice == 4):
employee.deleteEmployee();
elif(choice == 0):
goOn = False;
else:
print "Wrong Choice!!!";
emp = Employee();
emp.main();
Here I am importing this class:
class FileHandeling:
def createFile(fo,numOfRecords,data,counterFile):
#Getting the value of counter
frc = open(counterFile,"r");
counter = int(frc.read());
frc.close();
#Taking input and writing to the file
for i in range(counter,numOfRecords+counter):
string = str(i)+data[i];
fo.write(string);
counter += 1;
#Writing back to counter the updated value.
fwc = open(counterFile,"w");
fwc.write(str(counter)+"\n");
fwc.close();
def readFile(fo,searchStr,criteria):
line = fo.readline();
string = [];
while line:
entries = line.split();
if(searchStr == entries[criteria]):
string.append(line);
line = fo.readline();
return string;
def printFile(fo):
fo.seek(0);
lines = fo.readlines();
print "The File: "
for line in lines:
print line;
def updateRecord(fo,fileLoc,updateStr,lineNum):
#Replacing the given record with he updated record and writing back to file
lines = fo.readlines();
fwu = open(fileLoc, "w");
lines[lineNum]= updateStr;
for line in lines:
fwu.write(line);
fwu.close();
def deleteRecord(fo,fileLoc,lineNum):
#Deleting the record
lines = fo.readlines();
fwu = open(fileLoc, "w");
lines.pop(lineNum);
#Correcting the Employee Ids and Writing Back to File
for line in lines:
entry1, entry2, entry3, entry4, entry5 = line.split();
entry1 = str(lines.index(line));
line = entry1+" "+entry2+" "+entry3+" "+entry4+" "+entry5+"\n";
fwu.write(line);
fwu.close();
#Reducing Counter value
frc = open(counterFile,"r");
counter = int(frc.read());
frc.close();
fwc = open(counterFile,"w");
fwc.write(str(counter-1)+"\n");
fwc.close();
In this code I am trying to replicate a database with the help of file but my code gives error saying that 'module' object has no attribute 'createFile'. I also tried creating packages and doing like in java but then it started saying that ImportError: No module named src.fileManipulation. they were just my folders in which I was working and wanted them as packages so I put an __init__.py in them and the tutorials said that this will help in making packages but that didn't happen and since both my files were in same directory I imported it directly but now it gives attribute error and I don't know what that means. Please Help.
I have executed the code in Python default IDLE after correcting some print statements. I am using Python3 so used print (" "). And the result was an endless loop of
Wrong Choice!!!
Press:
1 to enter a new employee
2 to search employee
3 to update employee
4 to delete employee
0 to exit
My kind requtest to you is to revise Python once again.

Python, Writing the file twice

I'm trying to get my code so it will update Y7,Set1.txt but it keeps writing the data inside it again, + my new data that was added.
My code below:
print("Registration System")
print("Make sure their is atleast one name in register!")
password = ("admin")
check = input("The Administration Password is: ")
if check == password:
input("Enter any key to continue ")
print("If their is no names in the register.txt\nThe script will stop working here!")
set1 = list()
set2 = list()
set3 = list()
set4 = list()
set5 = list()
with open("register.txt", "r") as register:
registers = [line.rstrip("\n") for line in register]
for pop in registers:
print(pop)
choice = input(
'Where would you like it to go? (Enter 1 - set1, enter 2 - set2)')
if choice == '1':
set1.append(pop)
elif choice == '2':
set2.append(pop)
elif choice == '3':
set3.append(pop)
elif choice == '4':
set4.append(pop)
elif choice == '5':
set5.append(pop)
with open("Y7,Set2.txt", "r") as Y7R:
Y7 = [line.rstrip("\n") for line in Y7R]
with open("Y7,Set2.txt", "w") as Y7Y:
data = (str(Y7) + str(set2))
Y7Y.writelines(data)
with open("Y7,Set1.txt", "r") as d:
Y7S = [line.rstrip("\n") for line in d]
with open("Y7,Set1.txt", "w") as Y7D:
data2 = str(Y7S) + str(set1)
Y7D.writelines(data2)
else:
print("Access Denied!")
However the text file keeps printing the previous values, + a lot of ///////
Anyway I can get my code just to add information to that file, without adding all the /// and previous names? Thanks!
What's happening in the file is:
['[\'[\\\'[\\\\\\\'[\\\\\\\\\\\\\\\'[\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\'[\\\\\\\
PaulBrennan\\\\\\\\\
Open the file with "a" mode. "r" mode is used when the file only needs to be read and "w" for only writing (an existing file with the same name will be erased).
open("Y7,Set2.txt", "a")
You can check the docs.

global name 'doc' is not defined, trouble withvcall from one function to annother

I'm having some trouble with a piece of code I'm currently writing.
With the following code I get the NameError: global name 'doc' is not defined.
def createHtml():
name = input("\nEnter the name for your HTML-page: ")
doc = open(name + ".html", 'w')
def createTitle():
print (t[0], file=doc) #<!DOCTYPE html>
print (t[1], file=doc) #<html>
print (t[2], file=doc) #<head>
title = input("Enter your title here: ")
print (" <title>",title,"</title>", file=doc)
print (t[3], file=doc) #</head>
I know it's because the doc is only defined in the createHtml-function. But how do I get it to work if I want the same doc to work when called in a different function? I cant leave it out of the createHtml-function because it will mess up my program since I have a menu which allows the user to choose from the different functions.
Like this:
while True:
menu = input("\nPress 1 to enter the file name for the HTML-page"
"\nPress 2 to enter title for the HTML-page"
"\nPress 3 to start entering code in body"
"\nPress 4 to exit\n")
if menu == "1":
createHtml()
elif menu == "2":
createTitle()
elif menu == "3":
createBody()
else:
print ("Good bye!")
break
doc.close()
And the doc is defined by the name variable in:
name = input("\nEnter the name for your HTML-page: ")
Is there anyway to get doc from the createHtml-function to my other functions?
What about wrapping the functions inside a class?
class HtmlBuilder(object):
def __init__(self):
self.doc = None
def createHtml(self):
name = input("\nEnter the name for your HTML-page: ")
self.doc = open(name + ".html", 'w')
def createTitle(self):
print (t[0], file=self.doc) #<!DOCTYPE html>
print (t[1], file=self.doc) #<html>
print (t[2], file=self.doc) #<head>
title = input("Enter your title here: ")
print (" <title>",title,"</title>", file=doc)
print (t[3], file=self.doc) #</head>
def Dispose(self):
self.doc.flush()
self.doc.close()
And just use it like this:
hb = HtmlBuilder()
while True:
menu = input("\nPress 1 to enter the file name for the HTML-page"
"\nPress 2 to enter title for the HTML-page"
"\nPress 3 to start entering code in body"
"\nPress 4 to exit\n")
if menu == "1":
hb.createHtml()
elif menu == "2":
hb.createTitle()
elif menu == "3":
hb.createBody()
else:
print ("Good bye!")
break
hb.Dispose()
At the end of the day, this is a perfect use case for Object Oriented Programming isn't it? After this, a lot of good improvements can be done.
For example:
Replace the print statements from the function to the outer code.
Make your methods testable.
Unit testing.
GOOD STUFF :D
Your function createHtml() function will need to return doc, which you can then pass to createTitle(). Something like this:
def createHtml():
name = input("\nEnter the name for your HTML-page: ")
doc = open(name + ".html", 'w')
return doc
So then in your while loop:
doc = createHtml()
and then you can pass it to the other functions:
createTitle(doc)
Note that it doesn't have to be called the same thing in each function.

Personal archive tool, looking for suggestions on improving the code

i've written a tool in python where you enter a title, content, then tags, and the entry is then saved in a pickle file. it was mainly designed for copy-paste functionality (you spot a piece of code you like on the net, copy it, and paste it into the program), not really for handwritten content, though it does that with no problem.
i mainly did it because i'm always scanning through my pdf files, books, or the net for some coding example of solution that i'd already seen before, and it just seemed logical to have something where you could just put the content in, give it a title and tags, and just look it up whenever you needed to.
i realize there are sites online that handle this ex. http://snippets.dzone.com, but i'm not always online when i code. i also admit that i didn't really look to see if anyone had written a desktop app, the project seemed like a fun thing to do so here i am.
it wasn't designed with millions of entries in mind, so i just use a pickle file to serialize the data instead of one of the database APIs. the query is also very basic, only title and tags and no ranking based on the query.
there is an issue that i can't figure out, when you are at the list of entries there's a try, except clause where it tries to catch a valid index (integer). if you enter an inavlid integer, it will ask you to enter a valid one, but it doesn't seem to be able to assign it to the variable. if you enter a valid integer straightaway, there are no problems and the entry will display.
anyway let me know what you guys think. this is coded for python3.
main file:
#!usr/bin/python
from archive_functions import Entry, choices, print_choice, entry_query
import os
def main():
choice = ''
while choice != "5":
os.system('clear')
print("Mo's Archive, please select an option")
print('====================')
print('1. Enter an entry')
print('2. Lookup an entry')
print('3. Display all entries')
print('4. Delete an entry')
print('5. Quit')
print('====================')
choice = input(':')
if choice == "1":
entry = Entry()
entry.get_data()
entry.save_data()
elif choice == "2":
queryset = input('Enter title or tag query: ')
result = entry_query('entry.pickle', queryset)
if result:
print_choice(result, choices(result))
else:
os.system('clear')
print('No Match! Please try another query')
pause = input('\npress [Enter] to continue...')
elif choice == "3":
queryset = 'all'
result = entry_query('entry.pickle', queryset)
if result:
print_choice(result, choices(result))
elif choice == "4":
queryset = input('Enter title or tag query: ')
result = entry_query('entry.pickle', queryset)
if result:
entry = result[choices(result)]
entry.del_data()
else:
os.system('clear')
print('No Match! Please try another query')
pause = input('\npress [Enter] to continue...')
elif choice == "5":
break
else:
input('please enter a valid choice...')
main()
if __name__ == "__main__":
main()
archive_functions.py:
#!/bin/usr/python
import sys
import pickle
import os
import re
class Entry():
def get_data(self):
self.title = input('enter a title: ')
print('enter the code, press ctrl-d to end: ')
self.code = sys.stdin.readlines()
self.tags = input('enter tags: ')
def save_data(self):
with open('entry.pickle', 'ab') as f:
pickle.dump(self, f)
def del_data(self):
with open('entry.pickle', 'rb') as f:
data_list = []
while True:
try:
entry = pickle.load(f)
if self.title == entry.title:
continue
data_list.append(entry)
except:
break
with open('entry.pickle', 'wb') as f:
pass
with open('entry.pickle', 'ab') as f:
for data in data_list:
data.save_data()
def entry_query(file, queryset):
'''returns a list of objects matching the query'''
result = []
try:
with open(file, 'rb') as f:
entry = pickle.load(f)
os.system('clear')
if queryset == "all":
while True:
try:
result.append(entry)
entry = pickle.load(f)
except:
return result
break
while True:
try:
if re.search(queryset, entry.title) or re.search(queryset, entry.tags):
result.append(entry)
entry = pickle.load(f)
else:
entry = pickle.load(f)
except:
return result
break
except:
print('no entries in file, please enter an entry first')
pause = input('\nPress [Enter] to continue...')
def choices(list_result):
'''takes a list of objects and returns the index of the selected object'''
os.system('clear')
index = 0
for entry in list_result:
print('{}. {}'.format(index, entry.title))
index += 1
try:
choice = int(input('\nEnter choice: '))
return choice
except:
pause = input('\nplease enter a valid choice')
choices(list_result)
def print_choice(list_result, choice):
'''takes a list of objects and an index and displays the index of the list'''
os.system('clear')
print('===================')
print(list_result[choice].title)
print('===================')
for line in list_result[choice].code:
print(line, end="")
print('\n\n')
back_to_choices(list_result)
def back_to_choices(list_result):
print('1. Back to entry list')
print('2. Back to Main Menu')
choice = input(':')
if choice == "1":
print_choice(list_result, choices(list_result))
elif choice == "2":
pass
else:
print('\nplease enter a valid choice')
back_to_choices(list_result)
In the else, you call the main function again recursively. Instead, I'd do something like choice == "0", which will just cause the while loop to request another entry. This avoids a pointless recursion.

Categories