Learning python now.
I have the following program.
Why doesn't the program print anything after the last line?
It looks like "target" doesn't have any value that was written.
(even if I open the actual file, there are no values
why is that?
I tried adding that line above the "target.close" thinking the the file doesn't get written on until that line. That did not work either.
so what is the purpose of "target.close"?
how is that "target.truncate()" gets effect right away. After that command, and the script pauses on an input, if I open the file, I can see all the data it had has been erased away.
from sys import argv
script, filename = argv
print (f"We are going to erase {filename}")
print ("If you don't want that, press CTRL + C")
print ("if you want that, press ENTER")
input("? ")
print("Opening the file.......")
target = open(filename,"w+")
print("Truncating the file....")
target.truncate()
print("Finished Truncating")
print("Gimme 3 lines...")
Line1 = input("Line 1: ")
Line2 = input("Line 2: ")
Line3 = input("Line 3: ")
print("Writing these lines to the file")
target.write(Line1 + "\n")
target.write(Line2 + "\n")
target.write(Line3 + "\n")
print ("Finally, we close it")
target.close
input("Do you want to read the file now?")
print(target.read())
target.close
is missing the () call parenthesis. That is why nothing is written.
Then if you want to read the file, you will need to reopen it:
print(open(filename).read())
Solution
target.close is missing a parenthesis, i.e. it should be target.close().
But looking at your intention, it seems that you want to do target.flush() because you are also attempting target.read() soon after - you'll be unable to read from the file if you closed it.
Why does it happen
By default a certain amount of data that is written to the file is actually stored into a buffer - in memory - before it is actually written to the file. If you want to update the file immediately, you'll need to call the flush method, i.e. target.flush() Calling target.close() will automatically flush the data that has been buffered, hence why target.close() also updates the file similar to target.flush().
Related
I need help saving user input to a list after the program closes without a .text file (If possible)
I have it as let's say Test_Password = [""] I defined the list but every time the program opens I have to set it to a blank string because if I don't it won't be defined.
python
def Test1():
ABC_List = [""] #--i'll have to set the list to a blank string
def Test2() #--Another function to skip past the function that defines the list
user_input = input("Already have a letter: [Y]/[N]: ").upper()
if user_input == ("Y"):
print (" ")
x = input("What is your letter: ")
if x in ABC_List:
print (" ")
print ("Awesome! \n")
Test2()
else:
print ("You do not have a letter, go and add one! \n")
Test2() #-- I have no way of saving the data
elif user_input == ("N"):
print (" ")
x = input("Enter a letter! ")
if x in ABC_List:
print (" ")
print ("Sorry, letter is already in list! \n")
Test2()
else:
x.append(ABC_List)
Test()
print ("")
Test2()
Test2()
Test1()
If you want some data to be remembered after your program finishes running, it needs to be saved somewhere. A text file of some sort would be one option, but there are many others - a database, various cloud storage things, many many options. These will all be more work than a text file, though.
Why is it you need the data save, and why do you object to a text file? It would be easier to offer a helpful suggestion if we knew the answer to those questions.
Updated:
Since this is a homework question, I'll give you some hints rather than doing all the work for you. :-)
As you've told us, you'll be handing in just the script, so there may or may not be a data file when your script starts. You can try reading the file, and deal with the fact that the file might not be there. In Python, we deal with that kind of issue by catching exceptions.
Trying to load a list from a file, but falling back to an empty list if the file doesn't exist might look something like:
try:
with open('abc_list.txt') as abc_list_file:
abc_list = [value.strip() for value in abc_list_file]
except IOError:
abc_list = []
You can add to this list as you want to in your program. When you have a list you want to save, do something like:
with open('abc_list.txt', 'w') as abc_list_file:
abc_list_file.writelines(abc_list)
You cannot save state without performing IO (input/output). If you cannot save to a local file, your only option is to IO to another machine (that is to say: send your data over the Internet).
Otherwise, to recover state from a file:
file = open('my_things.txt')
# strip() is needed because each line includes a newline character
# at the end
my_things = set(line.strip() for line in file)
file.close()
Verify if an item is in this set:
if "something" in my_things:
print("I found it!")
else:
print("No such thing!")
Add something in your set:
my_things.add('something')
Write items back to your file:
file = open('my_things.txt', 'w')
for item in my_things:
file.write(item + '\n')
file.close()
Combining file operations:
with open('my_things') as file:
my_things = set(line for line in file)
with open('my_things.txt', 'w') as file:
file.write(item + '\n')
So, I am at exercise 16 of Zed Shaw's Python book.
I thought of trying out both append and truncate on the same file. I know, this does not make sense. But, I am new and I am trying to learn what would happen if I used both.
So, first I am opening the file in append mode and then truncating it and then writing into it.
But, the truncate is not working here and whatever I write gets appended to the file.
So, can someone kindly explain why the truncate would not work ? Even though I am opening the file in append mode first, I believe I am calling the truncate function after that and it should have worked !!!
Following is my code:
from sys import argv
script, filename = argv
print "We're going to erase %r." %filename
print "If you don't want that. hit CTRL-C (^C)."
print "If you do want that, hit RETURN."
raw_input("?")
print "Opening the file..."
target = open(filename, 'a')
print "Truncating the file. Goodbye!"
target.truncate()
print "Now I'm going to ask you for three lines."
line1 = raw_input("line 1: ")
line2 = raw_input("line 2: ")
line3 = raw_input("line 3: ")
print "I'm going to write these to the file."
target.write(line1 + "\n" + line2 + "\n" + line3)
print "And finally, we close it."
target.close()
Truncate the file’s size. If the optional size argument is present, the file is truncated to (at most) that size. The size defaults to the current position.
When you open your file with 'a' mode, the position is at the end of the file.
You can do something like this
f = open('myfile', 'a')
f.tell() # Show the position of the cursor
# As you can see, the position is at the end
f.seek(0, 0) # Put the position at the begining
f.truncate() # It works !!
f.close()
The argument 'a' opens the file for appending. You will need to use 'w' instead.
I am currently on Excercise 16 in Learn Python the Hard Way and i'm having a problem with my code where it will write onto the file, but my final print command does not print the contents of the file onto the console. On my command line, it just comes up with a couple of lines of blank space.From my understand "r+"opens it in read and write mode, but the computer cannot to read it.
Could someone tell me whats wrong with it please? Any help would be appreciated :)
from sys import argv
script, file = argv
print "The name of the file is %s" % file
filename = open(file,"r+")
print "First we must write something in it "
print "Do you want to continue?Press CTRL-C if not."
raw_input()
print "Type the first line of the text"
line1 = raw_input(">")+"\n"
print "Type the second line of text"
line2 = raw_input(">")+"\n"
print "Type the third line of text"
line3 = raw_input(">")+"\n"
sum_line = line1 + line2 + line3
print "Now I will write it to the file"
filename.write(sum_line)
print "The file now says:"
#This line here does not print the contents of the file
print filename.read()
filename.close()
As included in the first answer, after writing the offset will be pointing to the end of the file. However, you don't need to close the file and reopen it. Rather do this before reading it :
filename.seek(0)
That will reset the offset at the start of the file.
Then simply read it.
filename.read()
Since you wrote into the file, the offset after writing will point to the end of the file. At that point, if you want to read the file from the beginning you'll have to close it and re-open it.
By the way, since Python 2.5 the with statement is supported and recommended to use, for example:
with open('yourfile', 'r') as f:
for line in f:
...
Using with will take care of closing the file for you!
Without having to close then reopen the file you can add filename.seek(0) which will take it back to the top of the file.
filename = open('text.txt',"r+")
print(filename.read())
lin = input()
filename.write(lin)
filename.seek(0) # take it back to top, 0 can be changed to whatever line you want
print(filename.read())
filename.close()
I am doing Learn Python the Hard Way and am on exercise 16. The study drill says to write a script using read and argv.
My code is as follows:
from sys import argv
script, file_name, pet_name = argv
print "Ah, your pet's name is %r." %pet_name
print "This will write your pet's name in a text file."
print "First, this will delete the file. "
print "Proceeding..."
writefile = open(file_name, 'w')
writefile.truncate()
writefile.write(pet_name)
writefile.close
raw_input("Now it will read. Press ENTER to continue.")
readfile = open(file_name, "r")
print readfile.read()
The code works until the end. When it says to print the file, the command line gives a blank line.
PS C:\Users\[redacted]\lpthw> python ex16study.py pet.txt jumpy
Ah, your pet's name is 'jumpy'.
This will write your pet's name in a text file.
First, this will delete the file.
Proceeding...
Now it will read. Press ENTER to continue.
PS C:\Users\[redacted]\lpthw>
I am not sure why the script is just printing a blank file.
You never called the writefile.close() method:
writefile.write(pet_name)
writefile.close
# ^^
Without closing the file, the memory buffer to help speed writing never gets flushed and the file effectively remains empty.
Either call the method:
writefile.write(pet_name)
writefile.close()
or use the file as a context manager (with the with statement) to have Python close it for you:
with open(file_name, 'w') as writefile:
writefile.write(pet_name)
Note that the writefile.truncate() call is entirely redundant. Opening a file in write mode ('w') always truncates the file already.
I am currently reading "Learn Python the hard way" and have reached chapter 16. I can't seem to print the contents of the file after writing to it. It simply prints nothing.
from sys import argv
script, filename = argv print "We are going to erase the contents of %s" % filename print "If you don\'t want that to happen press Ctrl-C"
print "If you want to continue press enter"
raw_input("?") print "Opening the file..." target = open(filename, "w")
print "Truncating the file..." target.truncate()
print "Now i am going to ask you for 3 lines"
line_1 = raw_input("Line 1: ")
line_2 = raw_input("Line 2: ")
line_3 = raw_input("Line 3: ")
final_write = line_1 + "\n" + line_2 + "\n" + line_3
print "Now I am going to write the lines to %s" % filename
target.write(final_write)
target.close
print "This is what %s look like now" %filename
txt = open(filename)
x = txt.read() # problem happens here
print x
print "Now closing file"
txt.close
You're not calling functions target.close and txt.close, instead you're simply getting their pointers. Since they are functions (or methods, to be more accurate) you need () after the function's name to call it: file.close().
That's the problem; you open the file in write mode which deletes all the content of the file. You write in the file but you never close it, so the changes are never committed and the file stays empty. Next you open it in read mode and simply read the empty file.
To commit the changes manually, use file.flush(). Or simply close the file and it will be flushed automatically.
Also, calling target.truncate() is useless, since it's already done automatically when opening in write mode, as mentioned in the comments.
Edit: Also mentioned in the comments, using with statement is quite powerful and you should use it instead. You can read more of with from http://www.python.org/dev/peps/pep-0343/, but basically when used with files, it opens the file and automatically closes it once you unindent. This way you don't have to worry about closing the file, and it looks much better when you can clearly see where the file is being used, thanks to the indentation.
Quick example:
f = open("test.txt", "r")
s = f.read()
f.close()
Can be done shorter and better looking by using with statement:
with open("test.txt", "r") as f:
s = f.read()