open() method doesn't open specified .txt file - python

I am made a file where i can reference functions and i thought that it would be fun to make a program to add text to the file, and when i try to open the file, it doesn't show any errors, but when i go and check the file there's nothing there.
My code:
ime_funk = input("Ime funkcije: ")
x = 0
funk = ""
while True:
vseb_funk = input("Kopiraj eno, pa po eno vrstico funkcije, ko si končal napiši končano: ")
if vseb_funk == "končano":
break
else:
funk += "\n "+vseb_funk
mark = open("test.txt", "a")
mark.write("\n" + ime_funk + "\n" + funk)
Don't pay attention to the variable names and strings, as that's not important.
Also I am using replit if that's important.
I have no idea why it doesn't work.
i have tried mark = open("test.txt", "w") but same story.

you need to add this line to your code
mark.close()
or what you can do I replace this part of the code
mark = open("test.txt", "a")
mark.write("\n" + ime_funk + "\n" + funk)
with this code:
with open("test.txt", "a") as mark:
mark.write("\n" + ime_funk + "\n" + funk)

A file write in python does not happen untill you call file.flush(). This is usually called automatically when you close the file but in your example you are never closing the file. Try:
ime_funk = input("Ime funkcije: ")
x = 0
funk = ""
while True:
vseb_funk = input("Kopiraj eno, pa po eno vrstico funkcije, ko si končal napiši končano: ")
if vseb_funk == "končano":
break
else:
funk += "\n "+vseb_funk
mark = open("test.txt", "a")
mark.write("\n" + ime_funk + "\n" + funk)
mark.close()
or even better try using the with statement:
with open("test.txt", "a") as mark:
mark.write("\n" + ime_funk + "\n" + funk)
this way close() is called automatically

Related

How to space items?

import os
s = os.listdir("qwe")
f = open("asd.txt", "w")
for i in range(0, 100):
try:
f.writelines(s[i] + ":" + "\n")
f.writelines(os.listdir("qwe\ ".strip() + s[i] + "\Wallets"))
f.writelines("\n" + "\n")
except:
continue
It prints data like this:
dsadasda:
ada.txtli.pysda.txt
elele:
erti:
file.txt
jhgjghjgh:
new.txtpy.py
lolo:
sdada:
If there are lots of things in wallet it prints them together, how can i space between them?
you may write your code as this way
import os
s = os.listdir("qwe")
try:
with open("asd.txt", "a") as f: # opening file once
for i in range(0, 100):
f.writelines(s[i] + ":" + "\n")
print(s[i] + ":" + "\n")
f.writelines(os.listdir("qwe\ ".strip() + s[i] + "\Wallets"))
print(os.listdir("qwe\ ".strip() + s[i] + "\Wallets"))
f.writelines("\n" + "\n")
except:
pass
this is happening because you open the file for each loop so it doesn't write anything in your file
,
another thing that you are opening file in writing mode which means that it will erase the content of the file and replace it with the new one

How can I count and display the amount of times my program has been run?

I am making a text based game that once finished should write certain variables to a text file:
==============
Story0:
-----------
Players name: name
Players characteristic: characteristic
This works fine, however what I wish to implement is a way for the function this
text comes from to also display which story it is generating meaning that it would write: StoryX on the X'th time that the program has been run.
I am unfamiliar with writing to and reading from python files and I'm afraid I am very far off what would be the best solution. The following code represents what I have so far (providing an error):
def Endscript(numberofcycles):
with open("playerstories.txt", 'a') as f:
f.write("================\n")
f.write("Story" + str(numberofcycles) + ": \n")
f.write("-----------\n")
f.write("Players name: " + Player.name)
f.write("\n")
f.write("Players characteristic: " + Player.char)
f.write("\n")
with open("number.txt", "r") as f:
numberofcycles = f.readline()
numberofcycles = int(numberofcycles)
numberofcycles += 1
with open("number.txt", "w") as f:
numberofcycles = str(numberofcycles)
f.write(numberofcycles)
What I have attempted to do here is to change the value of a number, (yes just one number) from within the number.txt file in accordance with the changing X value.
Thank you for any help you can provide
Is this what you mean?
def Endscript():
with open("playerstories.txt", 'a') as f:
with open("number.txt", "r") as file:
numberofcycles = file.readline()
numberofcycles = int(numberofcycles)
f.write("================\n")
f.write("Story" + str(numberofcycles) + ": \n")
f.write("-----------\n")
f.write("Players name: " + Player.name)
f.write("\n")
f.write("Players characteristic: " + Player.char)
f.write("\n")
with open("number.txt", "w") as f:
numberofcycles += 1
numberofcycles = str(numberofcycles)
f.write(numberofcycles)
The error is caused by the undefined numberofcycles, if so it is because you haven't read into the txt file to retrieve the numberofcycles.
You have the right idea, just remember that each run your game will be a completely independent process so your Endscript() function really does not know the numberofcycles unless you have already read that from disk. Here is quick function to access a single file and increment the value each time, returning that value for your use.
import os
def increment_counter(file_name):
if not os.path.exists(file_name):
with open(file_name, 'w') as fp:
fp.write("1")
return 1
else:
with open(file_name, 'r') as fp:
current_count = int(fp.read().strip())
with open(file_name, 'w') as fp:
fp.write(str(current_count + 1))
return current_count + 1
fname = 'test_counter.txt'
print(increment_counter(fname))
print(increment_counter(fname))
print(increment_counter(fname))
print(increment_counter(fname))
Output:
1
2
3
4
You can couple this with a reset_counter() which just deletes the file to reset it

ValueError: I/O operation on closed file. -- For Loop

I've seen questions like this but mine is slightly different as I don't know where to indent because I'm using a 'for' loop instead of 'with'.
f = open("Roll_List", "r+")
for myline in f:
print (myline)
if CurrentUser in myline:
x = myline.split()
print (x[1])
s = str(int(x[1]) + z)
f.write(CurrentUser + " " + s)
f.close()
Try doing f.close outside the for loop
f = open("Roll_List", "r+")
for myline in f:
print (myline)
if CurrentUser in myline:
x = myline.split()
print (x[1])
s = str(int(x[1]) + z)
f.write(CurrentUser + " " + s)
f.close()
Use a with statement to automatically close the file after you're done with it.
with open("Roll_List", "r+") as f:
for myline in f:
print(myline)
if CurrentUser in myline:
x = myline.split()
print(x[1])
s = str(int(x[1]) + z)
f.write(CurrentUser + " " + s)

writing data in file using python

I am new in programming. Just bought a book for beginners in Python. In it I got this code:
name = input("name")
email = input("whats ure email:)
favoriteband = input("ure fav band")
outputString = name + "|" email + "|" + favoriteband
fileName = name + ".txt"
file = open(fileName, "wb")
file.write (outputString)
print (outputString , " saved in ", fileName)
file.close ()
According to book its fine but I got this error:
TypeError: a bytes-like object is required, not 'str'
I got no clue how to fix it and book isn't explaining this as well.
Let's go through this:
name = input("Your name: ")
email = input("Your email: ")
The close quotes are needed as has been pointed out.
outputString = name + "|" + email + "|" + favoriteband
outputString was missing a + before email
Finally, we need to rewrite you file management:
with open(fileName, "a") as file:
file.write (outputString)
print (outputString , " saved in ", fileName)
Writing this as a with statement guarantees it will close. Using open(..., "a") opens the file in "append" mode and lets you write multiple strings to a file of the same name.
Finally, if I can editorialize, I am not a fan of this book so far.
Edit: here is the whole code with fixes, in hopes of getting you there.
name = input("name")
email = input("whats ure email:")
favoriteband = input("ure fav band")
outputString = name + "|" + email + "|" + favoriteband
fileName = name + ".txt"
with open(fileName, "a") as file:
file.write (outputString)
print (outputString , " saved in ", fileName)
You can verify it works with:
with open(fileName, "r") as file:
print(file.read())
I did some editing (closing quotes and a missing +):
name = input("name:")
email = input("whats ure email:")
favoriteband = input("ure fav band:")
outputString = name + " | " + email + " | " + favoriteband
fileName = name + ".txt"
file = open(fileName, "w") #opened in write mode but not in binary
file.write (outputString)
print (outputString , " saved in ", fileName)
file.close()
You're getting that error because you're writing in binary mode, hence the b in wb for
file = open(fileName, "wb")
Try this instead :
file = open(fileName, "w")

Python export to file via ofile without bracket characters

I successfully simplified a python module that imports data from a spectrometer
(I'm a total beginner, somebody else wrote the model of the code for me...)
I only have one problem: half of the output data (in a .csv file) is surrounded by brackets: []
I would like the file to contain a structure like this:
name, wavelength, measurement
i.e
a,400,0.34
a,410,0.65
...
but what I get is:
a,400,[0.34]
a,410,[0.65]
...
Is there any simple fix for this?
Is it because measurement is a string?
Thank you
import serial # requires pyserial library
ser = serial.Serial(0)
ofile = file( 'spectral_data.csv', 'ab')
while True:
name = raw_input("Pigment name [Q to finish]: ")
if name == "Q":
print "bye bye!"
ofile.close()
break
first = True
while True:
line = ser.readline()
if first:
print " Data incoming..."
first = False
split = line.split()
if 10 <= len(split):
try:
wavelength = int(split[0])
measurement = [float(split[i]) for i in [6]]
ofile.write(str(name) + "," + str(wavelength) + "," + str(measurement) + '\n')
except ValueError:
pass # handles the table heading
if line[:3] == "110":
break
print " Data gathered."
ofile.write('\n')
do this:
measurement = [float(split[i]) for i in [6]]
ofile.write(str(name) + "," + str(wavelength) + "," + ",".join(measurement) + '\n')
OR
ofile.write(str(name) + "," + str(wavelength) + "," + split[6] + '\n')

Categories

Resources