Cannot write in text file in python program - python

So I am making a python game and everything in the python programs is fine except for the writing part
Here is a part of GameFile2.py:
class lostToss():
def botChoose(self):
print("Bot is choosing between batting and bowling.")
for dot in range(5):
print((dot + 1) * ".")
time.sleep(0.25)
for x in range(10):
print("")
choices = ['Bat', 'Bowl']
botting = random.choice(choices)
print(f"And the bot has chose to {botting}")
time.sleep(1)
if botting == "Bat":
f = open("GamePoints.txt","w")
with open('GamePoints.txt, 'a+') as f:
f.write('52L05yt0smdwPMA4wgdTUF7Yh4dLT')
print('ok')
time.sleep(10)
import GameFile3
elif botting == "Bowl":
file = open("GamePoints.txt","w+")
with open('GamePoints.txt', 'a+') as file:
file.write('69L05yt0smdwPMA4wgdLOL7Yh4dLT')
time.sleep(2)
import GameFile3
The problem is in the 15th and 22nd line, I ran the file many times and the "ok" text
was printed but the code couldn't be written in the file.
Can anyone help?

Omit the file opening before the with statements. Like this
f = open("GamePoints.txt","w") # remove this line
with open('GamePoints.txt', 'a+') as f:
file = open("GamePoints.txt","w+") # remove this line
with open('GamePoints.txt', 'a+') as file:
In the first block, you are missing the closing quote after .txt.

Related

any way to print a specific string based off of a line of a file?

so I'm currently trying to print a list of cards in a text based card battler I'm making for a school project, and I'm wondering if I can get some help. I'm trying to print something different if a line in a file is 0 or 1, but I can't figure it out. thanks if you can help
def mainfunc():
while i<cardlist:
#if it's zero, do this
print("the card this line represents")
#if it's one, do this
print("locked")
#else, becasue if it's else then you're at the end of the file
print("your deck:")
#print your current deck
print("which card do you want to add?")
print(filelinecount("RIPScards"))
This is what I would do (UPDATED):
# For preventing unwanted behavior if this file ever gets imported in another:
if __name__ == "__main__":
with open(**insert file path here**, 'r') as f:
for line in f:
if line.strip() == "0":
print("the card this line represents")
elif line.strip() == "1":
print("locked")
else:
print("your deck")
print("which card do you want to add?")
print(filelinecount("RIPScards"))
You can read a file line-by-line with it open like so:
with open(**file path**, 'r') as f:
for line in f:
# Do stuff with the line here
Or you can read all the lines one time and close the file, then do stuff with the lines, like so:
f = open(**file name here**, 'r')
$lines = f.readlines()
f.close() # Make sure to close it, 'with open' method automatically does that for you, but manually opening it (like in this example) will not do it for you!
# Do stuff with it:
for line in lines:
# Do something with the line
Hopefully that helps!

in python 3.4, readline works fine alone, but dies in a 'with open' loop. Why?

infile = 'xyz.txt'
f = open(infile)
line = f.readline() # these lines are all read fine
print("line=",line)
line = f.readline()
print("line=",line)
line = f.readline()
print("line=",line)
pause()
f.close()
with open(infile) as f:
line = f.readline() # this reads the first line but
print("line=",line) # dies without a message on line 2
pause()
sys.exit
def pause():
c = input("\nEnter q to quit, anything else to continue\n")
if (c.lower()=='q'): sys.exit()
return (c)
Adding arguments to open, like 'r', 'ignore', encoding, etc. make no difference.
It happens on other input files as well, so it's not input specific.
It dies even without the pause in the loop
After the first line, it prints the line and the pause message,
and dies reading the second line.
Could this be a genuine compiler error?
You need to add a loop to iterate over the lines:
import sys
def pause():
c = input("\nEnter q to quit, anything else to continue")
if c.lower() == 'q':
sys.exit()
infile = 'ttest.csv' # <-- replace with your own file
with open(infile) as f:
for line in f:
print('line = ', line)
pause()
First of all, with (in this case with open) is not a loop, with is a statement (check out: What is the python keyword "with" used for?) , so try this:
import sys
infile = 'xyz.txt'
def pause():
c = input("\nEnter q to quit, anything else to continue\n")
return c
with open(infile,'r') as f:
for line in f:
print("Current line:",line)
d={'q':sys.exit}
d.get(pause().lower(), lambda: '')()
sys.exit()
And you're asking the wrong question, readline also works fine with 'with open',
You're title was "in python 3.4, readline works fine alone, but dies in a 'with open' loop. Why?" as mentioned above with is not a loop

Python: Writing to file using for loop

Using this Python code I get printed lines of file in UPPERCASE but file remains unchanged (lowercase.)
def open_f():
while True:
fname=raw_input("Enter filename:")
if fname != "done":
try:
fhand=open(fname, "r+")
break
except:
print "WRONG!!!"
continue
else: exit()
return fhand
fhand=open_f()
for line in fhand:
ss=line.upper().strip()
print ss
fhand.write(ss)
fhand.close()
Can you suggest please why files remain unaffected?
Code:
def file_reader(read_from_file):
with open(read_from_file, 'r') as f:
return f.read()
def file_writer(read_from_file, write_to_file):
with open(write_to_file, 'w') as f:
f.write(file_reader(read_from_file))
Usage:
Create a file named example.txt with the following content:
Hi my name is Dmitrii Gangan.
Create an empty file called file_to_be_written_to.txt
Add this as the last line file_writer("example.txt", "file_to_be_written_to.txt") of your .py python file.
python <your_python_script.py> from the terminal.
NOTE: They all must be in the same folder.
Result:
file_to_be_written_to.txt:
Hi my name is Dmitrii Gangan.
This program should do as you requested and allows for modifying the file as it is being read. Each line is read, converted to uppercase, and then written back to the source file. Since it runs on a line-by-line basis, the most extra memory it should need would be related to the length of the longest line.
Example 1
def main():
with get_file('Enter filename: ') as file:
while True:
position = file.tell() # remember beginning of line
line = file.readline() # get the next available line
if not line: # check if at end of the file
break # program is finished at EOF
file.seek(position) # go back to the line's start
file.write(line.upper()) # write the line in uppercase
def get_file(prompt):
while True:
try: # run and catch any error
return open(input(prompt), 'r+t') # r+t = read, write, text
except EOFError: # see if user if finished
raise SystemExit() # exit the program if so
except OSError as error: # check for file problems
print(error) # report operation errors
if __name__ == '__main__':
main()
The following is similar to what you see up above but works in binary mode instead of text mode. Instead of operating on lines, it processes the file in chunks based on the given BUFFER_SIZE and can operate more efficiently. The code under the main loop may replace the code in the loop if you wish for the program to check that it is operating correctly. The assert statements check some assumptions.
Example 2
BUFFER_SIZE = 1 << 20
def main():
with get_file('Enter filename: ') as file:
while True:
position = file.tell()
buffer = file.read(BUFFER_SIZE)
if not buffer:
return
file.seek(position)
file.write(buffer.upper())
# The following code will not run but can replace the code in the loop.
start = file.tell()
buffer = file.read(BUFFER_SIZE)
if not buffer:
return
stop = file.tell()
assert file.seek(start) == start
assert file.write(buffer.upper()) == len(buffer)
assert file.tell() == stop
def get_file(prompt):
while True:
try:
return open(input(prompt), 'r+b')
except EOFError:
raise SystemExit()
except OSError as error:
print(error)
if __name__ == '__main__':
main()
I suggest the following approach:
1) Read/close the file, return the filename and content
2) Create a new file with above filename, and content with UPPERCASE
def open_f():
while True:
fname=raw_input("Enter filename:")
if fname != "done":
try:
with open(fname, "r+") as fhand:
ss = fhand.read()
break
except:
print "WRONG!!!"
continue
else: exit()
return fname, ss
fname, ss =open_f()
with open(fname, "w+") as fhand:
fhand.write(ss.upper())
Like already alluded to in comments, you cannot successively read from and write to the same file -- the first write will truncate the file, so you cannot read anything more from the handle at that point.
Fortunately, the fileinput module offers a convenient inplace mode which works exactly like you want.
import fileinput
for line in fileinput.input(somefilename, inplace=True):
print(line.upper().strip())

How to make python continually save file io

I have the following code,
def main():
SucessCount = 0
line = []
StringList = ''
url = "https://api.steampowered.com/IDOTA2Match_570/GetMatchDetails/V001/?key=&match_id=1957663499"
http = urllib3.PoolManager()
for i in range(1860878309, 1860878309 + 99999999999999999 ):
with open("DotaResults.txt", "w") as file:
if SucessCount > 70000:
break
result = http.request('GET', 'https://api.steampowered.com/IDOTA2Match_570/GetMatchDetails/V001/?key=F878695BB3657028B92BCA60CEA03E16&match_id=' + str(i))
x = json.loads(result.data.decode('utf-8'))
if('error' in x['result']):
print("Not found")
else:
if validityCheck(x['result']['players']) == True and x['result']['game_mode'] == 22:
line = vectorList(x)
#print(line.count(1))
if(line.count(1) == 10 or line.count(1) == 11):
SucessCount += 1
print('Ok = ' + str(SucessCount))
print("MatchId = " + str(x['result']['match_id']))
StringList = ','.join([str(i) for i in line])
file.write(StringList + '\n')
if(SucessCount % 5 == 0):
file.flush()
file.close()
time.sleep(30)
The problem I am having is that when I press the stop button in pycharm(in normal running mode)nothing shows up in the file, even tho I am closing the file every time I loop. Does anybody know why or what i can do to fix this?
You need to make four changes:
Open the file before entering the for loop -- that is, swap the with statement and the for statement.
Open the file in "a" mode instead of "w" mode. "a" stands for "append". Right now, every time you reopen the file it erases everything you wrote to it before.
Call file.flush() immediately after file.write() (that is, before the if SucessCount % 5 == 0.)
Don't close the file before sleeping.
Incidentally, the word "success" is spelled with two Cs, and in Python you do not have to put parentheses around the controlling expression of an if statement.

Why doesn't this write data into the created file? Python

Why does this create the file but not write the code into it?
import os
#List for text
mainlist = []
#Definitions
def main():
print("Please Input Data(Type 'Done' When Complete):")
x = input()
if x.lower() == 'done':
sort(mainlist)
else:
mainlist.append(x)
main()
def sort(mainlist):
mainlist = sorted(mainlist, key=str.lower)
for s in mainlist:
finalstring = '\n'.join(str(mainlist) for mainlist in mainlist)
print(finalstring)
print("What would you like to name the file?:")
filename = input()
with open(filename + ".txt", "w") as f:
f.write(str(finalstring))
print("\nPress Enter To Terminate.")
c = input()
main()
#Clears to prevent spam.
os.system("cls")
The file is made, and the data is stored... But finalstring's content isn't written into it. The file remains blank.
You're calling sort(mainlist) multiple times and the file is being overwritten each time. Change the open mode to a like:
with open(filename + ".txt", "a") as f:
f.write(str(finalstring))
See http://docs.python.org/3.2/tutorial/inputoutput.html#reading-and-writing-files

Categories

Resources