I cannot let the list write in txt (python) - python

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)

Related

Remove comma in between each word in file

My problem is after running my code came expected output, but in file contains comma between each words.
My input file:
idNo;UserGroup;Name;Description;Owner;Visibility;Members
id;grp1;bhalaji;asdfgh;bhalaji;public
abc
def
ghi
id;grp2;bhalaji;asdfgh;bhalaji;private
abc
def
ghi
My code:
import csv
output = []
temp = []
currIdLine = ""
with( open ('usergroups.csv', 'r')) as f:
for lines in f.readlines():
line = lines.strip()
if not line:
print("Skipping empty line")
continue
if line.startswith('idNo'): # append the header to the output
output.append(line)
continue
if line.startswith('id'):
if temp:
print(temp)
output.append(currIdLine + ";" + ','.join(temp))
temp.clear()
currIdLine = line
else:
temp.append(line)
output.append(currIdLine + ";" + ','.join(temp))
print("\n".join(output))
with open('new.csv', 'w') as f1:
writer = csv.writer(f1)
writer.writerows(output)
Output of the code:
u,u,i,d,;,U,s,e,r,G,r,o,u,p,;,N,a,m,e,;,D,e,s,c,r,i,p,t,i,o,n,;,O,w,n,e,r,;,V,i,s,i,b,i,l,i,t,y,;,M,e,m,b,e,r,s ---> heading
i,d,:;,g,r,p,1,;,b,h,a,l,a,j,i,;,a,s,d,f,g,h,;,b,h,a,l,a,j,i,;,p,u,b,l,i,c,;,a,b,c,,d,e,f,,g,h,i
i,d,:;,g,r,p,2,;,b,h,a,l,a,j,i,;,a,s,d,f,g,h,;,b,h,a,l,a,j,i,;,p,r,i,v,a,t,e,;,a,b,c,,d,e,f,,g,h,i
My desired output:
uuid;UserGroup;Name;Description;Owner;Visibility;Members
id:grp1;bhalaji;asdfgh;bhalaji;public;abc,def,ghi
id:grp2;bhalaji;asdfgh;bhalaji;private;abc,def,ghi
I don't know what is the issue in my code. Can anyone help?
https://docs.python.org/3/library/csv.html#csv.csvwriter.writerows
writerows(rows) takes a list of lists, but in your code it is a list of strings.
I don't think you need the csv module at all.
with open('new.csv', 'w') as f1:
for row in output:
f1.write(row + '\n')
Taking advantage of range(start, stop, step=1) step, this becomes pretty easy.
obj = """idNo;UserGroup;Name;Description;Owner;Visibility;Members
id;grp1;bhalaji;asdfgh;bhalaji;public
abc
def
ghi
id;grp2;bhalaji;asdfgh;bhalaji;private
abc
def
ghi
"""
lines = obj.strip().split("\n")
output = [lines[0]]
for i in range(1, len(lines), 4):
output.append(lines[i] + ";" + ",".join(lines[i + 1 : i + 4]))
print("\n".join(output))
idNo;UserGroup;Name;Description;Owner;Visibility;Members
id:grp1;grp1;bhalaji;asdfgh;bhalaji;public;abc,def,ghi
id:grp2;grp2;bhalaji;asdfgh;bhalaji;private;abc,def,ghi

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

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

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)

How can I print a .txt to my .py?

How can I fix it, I'm trying to call a .txt file(dictionary) to my .py and I am trying to split the dictionary and call it with out the |.
For example:
Please | help me
Please : help me
My code:
def load_library(file):
with open(file,'rt') as x:
mylist = x.split("|")
for y in mylist:
mod = getattr(x, y)
return mod
From what I can understand, this is what you are trying to do.
def load_lib(file):
allTheData = []
with open(file,"r") as f:
for line in f:
data = line.split("|")
####DO something
# data[1] is the stuff after |
printAsYouWant(data)
## allTheData holds all the definitions
allTheData.append(data[0] + ":" + data[1])
printList(allTheData)
def printAsYouWant(data):
print(data[0] + ":" + data[1])
####PRINT THE DATA
def printList(yourData):
for i in yourData:
print(i)
You can modify printAsYouWant(data) to change your data out.
Or, as one function.
def load_lib(file):
allTheData = []
with open(file,"r") as f:
for line in f:
data = line.split("|")
####DO something
# data[1] is the stuff after |
print(data[0] + ":" + data[1])
allTheData.append(data[0] + ":" + data[1])
for i in allTheData:
print(i)
EDIT: From what I can see, this should work as you specify in your question.

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