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)
Related
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
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
I want to use writelines() to let the list write in txt, but after running, there's nothing in my txt. What's wrong with my code?
Help me if you could. Thank you!
example list(records): [['flower', '200'], ['ham', '60'], ['van', '150']]
I want to write in the txt as below:
flower 200
ham 60
van 50
my code:
def save(initial_money, records): # I need both so don't change.
with open('records.txt', 'w') as f:
first_line = str(initial_money) + "\n"
f.write(first_line)
return initial_money
L = []
for rec, amt in records:
all_rec = str(rec) + " " + str(amt) + "\n"
L.append(all_rec)
f.writelines(records) # must use writelines
return records
This should do:
def save(initial_money, records):
with open('records.txt', 'w') as f:
first_line = str(initial_money) + "\n"
f.write(first_line)
for rec, amt in records:
f.write(str(rec) + " " + str(amt) + "\n")
The first return closes the function, you don't need second return either, records is available as argument.
If you insist on using writelines, you can modify it like below:
def save(initial_money, records):
with open('records.txt', 'w') as f:
first_line = str(initial_money) + "\n"
f.write(first_line)
L = []
for rec, amt in records:
L.append(str(rec) + " " + str(amt) + "\n")
f.writelines(L)
I didn't succeed to understand what you need two arguments.
here is my code:
def save(initial_money,records):
first_line = str(initial_money) + "\n"
with open('records.txt', 'w') as f:
f.writelines(first_line)
for items in records:
f.writelines(f"{items[0]} {items[1]} ")
f.writelines('\n')
records = [['flower', '200'], ['ham', '60'], ['van', '150']]
initial_money = 0
save(initial_money, records)
Here is my code:
f = open("text.txt", "w+")
var2 = input()
f.write(var2'\n')
How can I make this work?
if var is a string, you can just do f.write(var + '\n'). If var is not a string, you will need to do f.write(str(var) + '\n')
This should work
f = open("text.txt", "w+")
var2 = input()
f.write(var2 + '\n')
f.close()
But, this is a better way to do it
with open("text.txt", "w+") as f:
f.write(var2 + '\n')
I wrote a script that will open my text file search for a certain word, then select the line that contains this word ans split it into three parts, then it chooses the part which is a number and add 1 to it, so every time I run the script one is added to this number. here is the script:
#!/usr/bin/env python
inputFile = open('CMakeLists.txt', 'r')
version = None
saved = ""
for line in inputFile:
if "_PATCH " in line:
print "inside: ", line
version = line
else:
saved += line
inputFile.close()
inputFile = open('CMakeLists.txt', 'w')
x = version.split('"')
print "x: ", x
a = x[0]
b = int(x[1]) + 1
c = x[2]
new_version = str(a) + '"' + str(b) + '"' + str(c)
print "new_version: ", new_version
inputFile.write(str(saved))
inputFile.write(str(new_version))
inputFile.close()
but my problem is that the new number is being written at the end of the file, I want it to stay in its original place. Any ideas ?
thanks
The problem is that you write the new version number after the original file (without the version line):
inputFile.write(str(saved))
inputFile.write(str(new_version))
You could fix it by saving the lines before and after the line that contains the version separately and then save them in the right order:
#!/usr/bin/env python
inputFile = open('CMakeLists.txt', 'r')
version = None
savedBefore = ""
savedAfter = ""
for line in inputFile:
if "_PATCH " in line:
print "inside: ", line
version = line
elif version is None:
savedBefore += line
else:
savedAfter += line
inputFile.close()
inputFile = open('CMakeLists.txt', 'w')
x = version.split('"')
print "x: ", x
a = x[0]
b = int(x[1]) + 1
c = x[2]
new_version = str(a) + '"' + str(b) + '"' + str(c)
print "new_version: ", new_version
inputFile.write(savedBefore)
inputFile.write(str(new_version))
inputFile.write(savedAfter)
inputFile.close()
Note: you might need to add some extra text with the version line to make it have the same format as the original (such as adding "_PATCH").
There is a lots to say on your code.
Your mistake is that you're writing your "saved" lines and after you are writing your modified version. Hence, this modified line will be written at the end of the file.
Moreover, I advice you to use with statements.
lines = []
with open('CmakeLists.txt', 'r') as _fd:
while True:
line = _fd.readline()
if not line:
break
if '_PATCH ' in line:
a, b, c = line.split('"')
b = int(b) + 1
line = '{} "{}" {}'.format(a, b, c)
lines.append(line)
with open('CmakeLists.txt', 'w') as _fd:
for line in lines:
_fd.write(line)
This code is untested and may contains some error... also, if your input file is huge, putting every lines in a list can be a bad idea.
#!/usr/bin/env python
inputFile = open('CMakeLists.txt', 'r')
version = None
saved = ""
for line in inputFile:
if "_PATCH " in line:
print "inside: ", line
version = line
x = version.split('"')
print "x: ", x
a = x[0]
b = int(x[1]) + 1
c = x[2]
new_version = str(a) + '"' + str(b) + '"' + str(c)
saved += new_version
else:
saved += line
inputFile.close()
inputFile = open('CMakeLists.txt', 'w')
inputFile.write(str(saved))
inputFile.close()
if a certain line is found, update its content and add to saved, once for loop ends, just write saved to file