Information is not being written into file in append mode [duplicate] - python

This question already has answers here:
File open and close in python
(2 answers)
Closed 5 months ago.
I'm a beginner programmer in python and my lecturer wants us to make a program from scratch specifically w hard code.
It was running well previously, but when I tried testing the program earlier, this part of the program started to run an error. It said it cannot run code on a closed file. Can anyone help point out where the problem is?
Thank you so much
def temporder():
allmenu = open("allmenu.txt","r")
temporder = open("neworder.txt","a")
entry = str.upper(input("Please enter a valid product code: "))
for lines in allmenu:
code,price = lines.split(",")
if (entry in code):
temporder.write("\n" + code + "," + price)
temporder.close()
allmenu.close()

You indented the last 2 lines temporder.close() and allmenu.close(), this means that the first time it executes the if condition, it closes both files. Put the last 2 lines in the same indent level as the for loop and it should work fine.

You need to move file close statements (file.close()) to outside the for loop. Your code checks the first line of allmenu file and then closes the file.

Related

How to stop a "for loop", and continue running the code later after manually inputting a command? [duplicate]

This question already has answers here:
Saving the state of a program to allow it to be resumed [duplicate]
(4 answers)
Closed last month.
I have a file that looks like this called myLoop.py
for i in range(100):
print(i)
I run the file like so: python3 myLoop.py
I want to stop the code after reaching i = 10
Then, I want to manually start the code again by typing python3 myLoop.py or whatever necessary into the terminal, to have the code pick up after i = 10.
Then, I want the code to then stop at i = 30, then continue via a manual command again until the code completes at i = 99.
To be clear, I want to manually send a statement to the terminal in order to have the code pick up where it left off.
I want to use the pickle module to accomplish this, here are some links I've looked through related to it:
https://docs.python.org/3/library/pickle.html
https://www.geeksforgeeks.org/understanding-python-pickling-example/
https://realpython.com/python-pickle-module/
How to stop a for loop while in execution
This post is said to be a duplicate of the following posts, but neither provide any examples of the use of the pickle module for this purpose. The first post simply has an embedded link of the first URL I've read, and the other provides an example of JSON's use case. This post is not a duplicate of either.
Saving the state of a program to allow it to be resumed
Best method of saving data
Maybe this can help you
start = 0
try:
with open("state.txt", "rt") as fp:
state = fp.read()
if int(state) > 0:
start = int(state) + 1
except:
pass
for i in range(start, 100):
print(i)
if i == 10 or i == 30:
with open("state.txt", "wt") as fp:
fp.write(f"{i}")
break

Writing output of python print() to file appears after process is killed / finished [duplicate]

This question already has answers here:
How can I flush the output of the print function?
(13 answers)
Closed 2 years ago.
I had several print() statements in my code. I want run the code overnight and have them write to file.
I tried redirecting output to file as:
python mycode.py >> log.txt
While python process is running, I cannot see anything written to file. When I kill the process and open the log file, I find the output in it.
Similar behavior was seen when I explicitlys specified file handle in the every print statement:
output_file = open('log.txt','w')
print('blablabla', file=output_file)
How can I make print to write the file immediately? Am I missing anything?
You are not seeing your changes right away because in some cases, due to buffering, changes made to a file may not show until you close the file.
To save changes without closing, please, refer to this page Can I save a text file in python without closing it?
Can you try this and tell me if it updates, immediately or not. I'm always using this syntax in PyCharm. I hope it works with u, too.
If you want to insert bunch of data one at time.
with open("log.txt", 'w') as test:
print ("hello world!", file=test)
If you want to insert data into .txt, then do some process, then back again to add more data to the .txt
test = open("log.txt", 'w')
print ("hello world!", file=test)
#==== Do some processes ====
print("This's the end of the file")
test.close()

problem with with-as statement as mentioned in learn python3 the hard way [duplicate]

This question already has answers here:
What is the python "with" statement designed for?
(11 answers)
Closed 4 years ago.
I've been reading the learn python3 the hard way book and in a exercise about python symbols he refers to a 'as' symbol and in the description it says "Part of the with-as statement" and the example format is "with X as Y: pass" but i couldn't find anything about such a thing online so I'm asking here.
Does anyone know anything about it?
and as a refrence it's exercise 37
The With x as y construct in python in called a context manager.
Context managers are used to properly manage resources. For example, if one is used to open a file, a context manager will ensure the file is closed.
with open('my_file.txt', 'r') as file:
for line in file:
print('{}'.format(line))
This is equivalent to:
file = open('my_file.txt') as file
for line in file:
print('{}.format(line))
file.close()
As you can see, the call to the close function is not necessary when you use a context manager.Its easy to forget to close the file, and this can lead to your system crashing if too many files are open. (There is a maximum number allowed by the operating system.)
See this link for more information and examples.

Python - print() - debugging -show file and line number [duplicate]

This question already has answers here:
filename and line number of Python script
(11 answers)
Closed 5 years ago.
When using print() in python, is it possible to print where it was called? So the output will look like var_dump in php with xdebug. Eg. I have script D:\Something\script.py, and at line 50, there is a print("sometest"), so the output will look like this:
D:\Somethinq\script.py:50 sometest
Or is there any module that could achieve this? In large projects, it's really hard to manage where these prints came from.
So, using answers provided in filename and line number of python script , this function can be called instead of print(), and prints line number before every output:
from inspect import currentframe
def debug_print(arg):
frameinfo = currentframe()
print(frameinfo.f_back.f_lineno,":",arg)

Python3 reading and writing .txt files [duplicate]

This question already has answers here:
What does "SyntaxError: Missing parentheses in call to 'print'" mean in Python?
(11 answers)
Closed 5 years ago.
I'm somewhat new to Python, but I have enough under my belt to know what I'm doing. What I'm trying to do is write a few lines for a .txt file (as well as a variable), and then print 5 of those characters.
import os
username = "Chad_Wigglybutt"
file = open("testfile.txt", "w")
file.write("Hello .txt file, ")
file.write("This is a test, ")
file.write("Can this write variables? ")
file.write("Lets see: ")
file.write(username)
file.close()
It then creates the file without issue, but when I add
print file.read(5)
to the code, it gives me a syntax error for file.read, and I have no clue why. I've been on the internet for a few hours now and I can't find anything. Either I'm extremely bad at google searching and I'm an idiot, or something's broken, or both. Any tips/ideas? :/
You're writing Python 3 code. In Python 3, print is a function, not a special statement. You need parentheses for function calls:
print(file.read(5))

Categories