Sorry for dragging the entire thread for a millennium and making it way too unsolvable, but I have solved majority of the problems, it's just that I want to fix my delete code but I have no idea where to start with it.
def delete_record():
with open('StudentDetails.csv', 'wb',) as csvfile:
csvFileWriter = csv.writer(csvfile)
a = delete_student_entry.get()
b = delete_password_entry.get()
csvFileWriter.writerow([a,b])
I want the program to take the input from the entry box in the window (as I am using Tkinter) and delete an entire row from the input. I will welcome any rewrites of the code as it will be a subroutine for my "delete student" menu (unconventional, I know, but using other forms of calling the subroutine will result in an error in which I had no choice but to do so...)
Do you mean deleting the row, which you get from your Entries, from your CSV file?
If so your answer can be found here:
using Python for deleting a specific line in a file
Related
Let me preface by saying I am very new to programming. I'm creating a fun program that I can use to start my day at work. One of the things I want it to do is display a random compliment. I made a text file that has multiple lines in it. How do I store that text file then open it?
I've opened text files before that were on my desktop but I want this one to be embedded in the code so when I compile the program I can take it to any computer.
I've googled a ton of different key words and keep finding the basics of opening and reading txt files but that's not exactly what I need.
Perhaps start with defining a default path to your file; this makes it easier to change the path when moving to another computer. Next, define a function in your program to read and return the contents of the file:
FILE_PATH = "my/path/to/file/"
def read_file(file_name):
with open(FILE_PATH + file_name) as f:
return f.read()
With that in place, you can use this function to read, modify, or display the file contents, for example to edit something from your file:
def edit_comments():
text = read_file("daily_comments.txt")
text = text.replace("foo", "foo2")
return text
There are obviously many ways to approach this task, this is just a simple example to get you started.
I am building a small tool in Python, the function of the tool is the following:
Open a master data file (cvs format)
open a log file (cvs format)
Request the user to select the pointer for the field that will need to be compared in both files.
Start comparing record by record
when the field is not found in the record proceed to look forward in the log file until the field can be found, in the meantime keep in memory the pointer for when the comparison will be continued.
Once the field is found proceed to cut the whole record off that line and place it in the right position
Here is an example :
Data file
"1","1234","abc"
"2","5678","def"
"3","9012","ghi"
log file
"1","1234","abc"
"3","9012","ghi"
"2","5678","def"
final log file :
"1","1234","abc"
"2","5678","def"
"3","9012","ghi"
I was looking in the cvs lib in python and the sqlite3 lib but there is nothing that seems to really do a swap in file so i was thinking that maybe i should just create a new file with all the records in order.
What could be done in this regard ? Is there a library or a command that can move records in an existing file ?
I would prefer to modify the existing file instead of creating a new one but if it's not possible i would just move to create a new one.
In addition to that the code i was planning to use to verify the files was this :
import csv
reader1 = csv.reader(open('data.csv', 'rb'), delimiter=',', quotechar='"'))
row1 = reader1.next()
reader2 = csv.reader(open('log.csv', 'rb'), delimiter=',', quotechar='"'))
row2 = reader2.next()
if (row1[0] == row2[0]) and (row1[2:] == row2[2:]):
#here it move to the next record
else:
#here it would run a function that replace the field
Please note that this piece of code was found at this page :
Python: Comparing specific columns in two csv files
(i don't want to take away the glory from another coder).
I just like it for it's simplicity.
Thanks to all for the attention.
Regards
Danilo
I want to modify one column in a .dpf file using Python with this library http://pythonhosted.org/dbf/. When I want to print out some column, it works just fine. But when I am trying to modify a column, I get error
unable to modify fields individually except in with or Process()
My code:
table = dbf.Table('./path/to/file.dbf')
table.open()
for record in table:
record.izo = sys.argv[2]
table.close()
In docs, they recommend doing it like
for record in Write(table):
But I also get an error:
name 'Write' is not defined
And:
record.write_record(column=sys.argv[2])
Also gives me an error that
write_record - no such field in table
Thanks!
My apologies for the state of the docs. Here are a couple options that should work:
table = dbf.Table('./path/to/file.dbf')
# Process will open and close a table if not already opened
for record in dbf.Process(table):
record.izo = sys.argv[2]
or
with dbf.Table('./path/to/file.dbf')
# with opens a table, closes when done
for record in table:
with record:
record.izo = sys.argv[2]
I have been trying to make a change to my dbf file for several days and searched and browsed several websites, this page was the only one that gave me a solution that worked. Just to add a little more information so that whoever lands here would understand the above piece of code that Ethan Furman shared.
import dbf
table = dbf.Table('your_dbf_filename.dbf')
# Process will open and close a table if not already opened
for record in dbf.Process(table):
record.your_column_name = 'New_Value_of_that_column'
Now, because you don't have a condition mentioned here, you would end you updating all the rows of your column. Remember, this statement will immediately reflect the new value in that column. So, the advice is to save a copy of this dbf file before making any edits to it.
I also tried the 2nd solution that Ethan mentions, but it throws an error that 'table' not defined.
I am brand new to Python (just started it 5 hours ago) but I have about a year of experience with Java. Anyways, the first program I wanted to make would create a sort of 'log book' of names/Birthdays. It prompts the User for the number of entries, then the names and birthdates. It is fairly simple and works fine. Each time you run the Program it appends the new Names/Birthdates, to the text file so The previous names/birthdates remain intact and the new ones appear at the end. However I wanted to be able to sort these entries by last name. I successfully create a way to sort them by last name (again its not to complex) however It only works if It is its own separate program. If i place the code at the end of my original program, It will sort as expected, however it will not sort any of the new entries made in the program, only the entries from the last time the program was run. I did close the file and re-open it in the code after the entries were made, however it still will not recognizes the changes made. Because Both programs function properly on their own, what do I need to do in order to implement these two pieces of code in the same program? Alternatively, would there be a way to run the second program from the first program?
Here is my programs code (BirthDates.txt is the text file were the entries are stored):
#IDLE 1.2.4
#Begin Entries
fileobja=open("BirthDates.txt","a")
dates=int(raw_input("Number of entries to add:"))
count=0
while count<dates:
fileobja.write("*NEW ENTRY*")
firstName=raw_input("Enter user's first name:")
lastName=raw_input("Enter user's last name:")
DOB=raw_input("Enter user's date of birth (MM/DD/YYYY):")
print lastName+","+firstName+"\n"+DOB
fileobja.write("\n")
fileobja.write(lastName+", "+firstName+"\n")
fileobja.write("("+DOB+")"+"\n"+"__________\n")
#print "dates=",dates
#print "count=",count
count=count+1
#print "count=",count
fileobja.close
#End Entries
This is the second Program:
#Begin Sorter
fileobjr=open("Birthdates.txt","r")
fileList=[]
tempString=""
tempStringCount=0
for line in fileobjr:
tempString="".join(line[0:])
#print "tempString="+tempString
fileList.append(tempString)
tempStringCount=tempStringCount+1
fileobjr.close
fileListLength=len(fileList)
#print fileListLength
chunks=(fileListLength)/4
sortCount=1
tempList=[]
while sortCount<fileListLength:
templine=fileList[sortCount]+fileList[sortCount+1]
tempList.append(templine)
sortCount=sortCount+4
writeCount=0
tempList.sort()
fileobjw=open("BirthDates.txt","w")
while writeCount<chunks:
#print tempList[writeCount]
fileobjw.write("*NEW ENTRY*\n")
fileobjw.write(tempList[writeCount])
fileobjw.write("__________")
fileobjw.write("\n")
writeCount=writeCount+1
fileobjw.close
#End Sorter
The problem is here:
fileobja.close
… and a few similar lines.
You're not calling the close method, you're just referencing it as a value. So, the file doesn't get closed, which means it doesn't get flushed, which means anything you've written to it may not be available to read yet.
To fix it, just call the method:
fileobja.close()
As a side note, it's usually easier to use a with statement, which takes care of closing the file when you exit the block inside it. (It's like a magic try/finally.) Instead of this:
f = open('foo', 'a')
do_stuff(f)
do_more_stuff(f)
# ...
f.close()
Do this:
with open('foo', 'a') as f:
do_stuff(f)
do_more_stuff(f)
# ...
I am having trouble writing this short program for my python class I was hoping someone could offer some assistance.
What I would like to accomplish:
1. Write a program that uses a while loop to accept input from the user (if the user presses Enter, exit the program).
2. Save the input to a file, then print it.
3. Upon starting, the program will display the current contents of the file.
Example:
Start program for first time.
Enter text: this is input
this is input.
Enter text: some more text
this is input. some more text.
When you start the program for a second time
this is input. some more text.
Enter text:
etc. etc.
What I have so far:
intext = open('user_input.txt','a')
intext.close()
string_input = input('Enter text: ')
while True:
open_input = open('user_input.txt','r')
if open_input:
for i in open_input:
print(i)
if string_input != "":
uinput = open('user_input.txt','a')
uinput.write(string_input + '.')
uinput.close()
rd = open('user_input.txt', 'r')
if rd:
for line in rd:
print(line)
if string_input == "":
t = open('user_input.txt', 'r')
for line in t:
print(line)
t.close()
break
Problems: Upon opening, any previously stored text does not display. If a user inputs text it prints in an infinite loop, and does not prompt to enter text again.
Positives: The input is recorded to the text file. If no text is entered, when exiting any previously entered text does display correctly.
Like I said, this is homework for me. I have searched for the answer, but I seem to be ripping the code apart and putting it back together only to get different errors. So some guidance on this would be greatly appreciated.
One thing I forgot to mention is that I am using Python 3.
Thanks again to David for helping me think more like a programmer. Here are the results:
intext = open('user_input.txt','r').readline()
print(intext)
while True:
string_input = input('Enter text: ')
if string_input == "":
t = open('user_input.txt', 'r').readline()
print(t)
break
if string_input != "":
d = open('user_input.txt', 'a')
d.write(string_input + '. ')
d.close()
n = open('user_input.txt', 'r').readline()
print(n)
I tried to keep the code as slim as possible, and it works now.
A couple questions additional questions that came out of this:
Do I need to close the file at the end? When I tried to close apnd and n , It gave me errors.
While looking for answers I came a across, this. Is it still best practice to use a "with" statement?
Example:
with open("x.txt") as f:
data = f.read()
do something with data
To be honest, your program as you've shown it is kind of a mess. I say this not to be insulting, but because you do have a pretty clear list of the steps your program needs to take, and I think you will wind up with a better understanding by scrapping your existing code and starting from scratch.
In your question, you listed the following steps:
Upon starting, display any previous content of the file
Use a while loop to
Accept input from the user
If the user presses Enter, exit the program
Save the input to a file
Print it (note: did you mean to print just the latest input, or everything in the file?)
Turning your overall task into a list of specific steps like this is probably 80% of the work of writing a computer program. All that's left to do is translate it into code. So I would suggest that you consider how to do each of these steps individually.
Write a code snippet to display the contents of a file
Write a code snippet to read a line of input from the user and store it in a variable
Write a code snippet to check the contents of a variable to see whether it's empty, and if so, exit
Write a code snippet to append the contents of a variable to a file
Write a code snippet to print the contents of a variable (or of a file, if that's what you meant to do)
Each of these can be done in one or two lines, so individually, you should have an easy time with them. Once you've done all the pieces, all you need to do is put them together:
# display the contents of the file
while True:
# read a line of input and store it in a variable
# check the contents of the variable to see if it's empty, and if so, exit
# append the contents of the variable to the file
# print the contents of the variable (or of the file)
Update: This is not a big deal, but you have an unnecessary if statement (the second one) in your revised program. Think about this: if string_input is empty, Python will execute the break statement, which terminates the loop immediately. So you'll only ever reach the second if statement if string_input is not empty. That means the condition string_input != "" is guaranteed to be true at that point in the program, and there's no need to check it.
Do I need to close the file at the end? When I tried to close apnd and n , It gave me errors.
Yes you do. Look at the pattern you used with d:
# open the file
d = open('user_input.txt', 'a')
# write to it (or read from it)
d.write(string_input + '. ')
# close it
d.close()
You should do the same thing every time you open a file, namely with intext, t, and n: open it, read from it, and then immediately close it.*
I'm guessing that the reason you encountered errors is that you tried to put the .close() statements at the end of the program, outside of the if statement and perhaps even outside of the while loop. That would give you a NameError because the variables n and t are not defined at those points in the program. They "expire" at the end of the block they are defined in. For more information on this, read up on scoping. (The Wikipedia article is probably not the best introduction, but you can search Stack Overflow and/or the web for more resources.)
While looking for answers I came a across, this. Is it still best practice to use a "with" statement?
Yes, the with statement is relatively new to Python and is the recommended way to do "quick" file I/O operations like this. Basically the with block takes care of closing the file at the end. For example, the code snippet above involving d is equivalent to
# open the file
with open('user_input.txt', 'a') as d:
# write to it (or read from it)
d.write(string_input + '. ')
# Python "automatically" closes it for you
*This "open-read/write-close" pattern of file access is usually a good idea. I've told you to use it in your program because it's important for you to learn how to split a program into small steps and convert each of the steps into code individually. But when you are writing a program that repeatedly writes things out to a file, or reads them in from a file, sometimes it is actually better to just open the file once in the beginning and just keep it open, rather than opening and closing it every time. If you are curious, one thing you could investigate is how to modify your program to reduce the number of times it has to open and close the file.
Use raw_input instead of input.
You forget to call input in the while loop
BTW, why not write data just at exit of the program instead of in each loop?