Python-Multiple writing the same line in txt file - python

I have code like this:
def export_devices():
code = input("Enter device code: ")
amount = int(input("How many devices you export: "))
with open("uredjaji.txt", "r+") as f:
current_position = 0
line = f.readline()
while line:
if line[:len(code) + 1] == code + ":":
line = line.rstrip()
amount_index = line.rfind(":") + 1
current_amount = int(line[amount_index:])
if amount > current_amount:
print("There no that many devices in stock...")
return
remaining_content = f.read()
f.seek(current_position)
f.truncate()
line = line[:amount_index] + str(current_amount - amount) + "\n"
f.write(line)
f.write(remaining_content)
return
current_position = f.tell()
line = f.readline()
with open('transakcije.txt','a') as transactions:
date = datetime.date.today().strftime('%d.%m.%Y.')
transactions.write("1" + ":" + str(amount) + ":" + "export" + ":" + str(date) + ":" + "username" + "\n")
print("Error device code: {}".format(code))
Now I would like to my "transakcije.txt" looks like this:
1:3:iznos:17.06.2017.:username
But it always append the same line for three times. With any other kind of indentation it won't append at all.
Also, my uredjaji.txt file looks like this:
tw004:Galaxy S5:Samsung:Mobilni telefon:3
tw002:Galaxy S6:Samsung:Mobilni telefon:1
tw001:Huawei P8:Huawei:Mobilni telefon:1
tw003:Huawei P9:Huawei:Mobilni telefon:100998
P.S: "username" should be variable from another function, so if someone could help me how to write that variable in this file I will be so thankfull. :)

When you open the file, you read a single line and then go into a while loop on the existence of line. If you do not get a match on the input code, you then attempt to, I suppose, reposition the file pointer with f.tell() but you do not do a seek. Thereafter, you read the file again and write transakcije.txt. Sadly, the original while loop is still in play, so you will write transakcije.txt multiple times.
It is not clear what you are attempting to achieve with this code but you need to sit down and rethink it from the ground up.
If it is some sort of stock reporting/replenishment routine, I can't help thinking that a database (sqlite3 as a simple starter) would be more appropriate that pulling ascii files apart.

Related

Python: Writing to file using while loop fails with no errors given

I am attempting to collect only certain type of data from one file. After that the data is to be saved to another file. The function for writing for some reason is not saving to the file. The code is below:
def reading(data):
file = open("model.txt", 'r')
while (True):
line = file.readline().rstrip("\n")
if (len(line) == 0):
break
elif (line.isdigit()):
print("Number '" + line + "' is present. Adding")
file.close()
return None
def writing(data):
file = open("results.txt", 'w')
while(True):
line = somelines
if line == "0":
file.close()
break
else:
file.write(line + '\n')
return None
file = "model.txt"
data = file
somelines = reading(data)
writing(data)
I trying several things, the one above produced a TypeError (unsupported operand). Changing to str(somelines) did solve the error, but still nothing was written. I am rather confused about this. Is it the wrong definition of the "line" in the writing function? Or something else?
See this line in your writing function:
file.write(line + '\n')
where you have
line = somelines
and outside the function you have
somelines = reading(data)
You made your reading function return None. You cannot concat None with any string, hence the error.
Assuming you want one reading function which scans the input file for digits, and one writing file which writes these digits to a file until the digit read is 0, this may help:
def reading(file_name):
with open(file_name, 'r') as file:
while True:
line = file.readline().rstrip("\n")
if len(line) == 0:
break
elif line.isdigit():
print("Number '" + line + "' is present. Adding")
yield line
def writing(results_file, input_file):
file = open(results_file, 'w')
digits = reading(input_file)
for digit in digits:
if digit == "0":
file.close()
return
else:
file.write(digit + '\n')
file.close()
writing("results.txt", "model.txt")

Readline printing just characters

I run this code in the Python IDLE, and it will only return the amount of letters specified instead of the line specified.
if os.path.exists(saveDir + name + '.txt') == True:
print('welcome back ' + name + '.')
file = open(saveDir + name + '.txt')
race = file.readline(1)
else:
race = intro()
When I print the race variable, it comes out as the G (The input name is Grant).
The text file looks like this
Grant
Human
What Am I doing wrong?
race = file.readline(1) returns 1 byte (character) of the line (see here). You want to return the entire line so call race = file.readline().
Are you trying to read a single line, or all the lines? file.readline() will return the first line of the file as a string. If called again, it will return the second line, and so on. You can also load all the lines of the file as a list with file.readlines(), and then get the first or second element by using [0] or [1], so file.readlines()[1] will yield "Human".
if os.path.exists(saveDir + name + '.txt') == True:
print('welcome back ' + name + '.')
file = open(saveDir + name + '.txt')
race = file.readline() # this reads one line at a time
raceType = file.readline() # this will give you the second line (human)
else:
race = intro()

Why doesn't this writing to file in python work?

The idea behind the following code is that the if the variable crop is already contained within the .txt file the variable quantity will be added on to the end of the same line as crop. This is my attempt at doing this, however it doesn't work: you really need to run it to understand, but, essentially, the wrong section of the list is added to, an ever expanding series of '/' appear and the line breaks disappear. Does anyone know how to modify this code so it functions properly?
What should be outputted:
Lettuce 77 88 100
Tomato 99
What actually is outputted:
["['\\n', 'Lettuce 77 \\n88 ', 'Tomato 88 ']100 "]
Code:
def appendA ():
with open('alpha.txt', 'r') as file_1:
lines = file_1.readlines()
for line in lines:
if crop in line:
index = lines.index(line)
line = str(line + quantity + ' ')
lines [index] = line
newlines = str(lines)
#The idea here is that the variable quantity is added onto the end
# of the same row as the entered crop in the .txt file.
with open('alpha.txt', 'w') as file_3:
file_3.write (newlines)
def appendB ():
with open('alpha.txt', 'a') as file_2:
file_2.write ('\n')
file_2.write (crop + ' ')
file_2.write (quantity + ' ')
crop = input("Which crop? ")
quantity = input("How many? ")
with open('alpha.txt', 'a') as file_0:
if crop in open('alpha.txt').read():
appendA ()
else:
appendB ()
Let's start! Your code should look something like this:
def appendA():
with open('alpha.txt', 'r') as file_1:
lines = []
for line in file_1:
if crop in line:
line = str(line.rstrip("\n") + quantity + "\n")
lines.append(line)
#The idea here is that the variable quantity is added onto the end
# of the same row as the entered crop in the .txt file.
with open('alpha.txt', 'w') as file_3:
file_3.writelines(lines)
def appendB():
with open('alpha.txt', 'a') as file_2:
file_2.write('\n')
file_2.write(crop + ' ')
file_2.write(quantity + ' ')
crop = "Whichcrop"
quantity = "+!!!+"
with open('alpha.txt') as file_0:
if crop in file_0.read():
print("appendA")
appendA()
else:
print("appendB")
appendB()
with open('alpha.txt', 'a') as file_0:
if crop in open('alpha.txt').read():
appendA ()
else:
appendB ()
Also you make several mistakes.
This line "with open('alpha.txt', 'a') as file_0:" open file with context for append in the end of file, but you dont use variable file_0. I think it's extra.
On next step you opened file for check "crop in open('alpha.txt').read()", but never close it.
["['\n', 'Lettuce 77 \n88 ', 'Tomato 88 ']100 "]
You get such a output because, you use write instead of writelines:
with open('alpha.txt', 'w') as file_3:
file_3.write (newlines)
Also you write in the file after each iteration, better to form a list of strings and then write to file.
newlines = str(lines) # you convert all lines list to str - so you get default conversion
and also you should replace whole file if you want to write in the middle
And you can also get read of appendB, because you still check every line and your code anyway is not optimal in terms of performance :)
from os import remove, close
def appendA(filename, crop, quantity):
result = []
exists = False
with open(filename, 'r') as file_1:
lines = file_1.readlines()
for line in lines:
if not crop in line:
result.append(line)
else:
exists = True
result.append(line.strip('\n') + quantity + '\n')
if not exists:
with open(filename, 'a') as file_2:
file_2.write ('\n' + crop + ' ' + quantity + ' ')
else:
tmp_file = filename + '.tmp'
with open(tmp_file, 'w') as file_3:
file_3.write(result)
remove(filename)
move(tmp_file, filename)
"str(lines)": lines is list type, you can use ''.join(lines) to
convert it to a string.
"line in lines": "line" end with a "\n"
Code indent error: "line newlines = ''.join(lines)" and the follow
"if crop in lines" is mistake, if crop named "AA" and "AABB", the
new input "AA" with return true, the quantity will be appended to
all lines including "AA" ,not only the "AA" line.
def appendA():
with open('alpha.txt', 'r') as file_1:
lines = file_1.readlines()
for line in lines:
if crop in line:
index = lines.index(line)
line = str(line.replace("\n", "") + ' ' + quantity + '\n')
lines[index] = line
newlines = ''.join(lines)
# The idea here is that the variable quantity is added onto the end
# of the same row as the entered crop in the .txt file.
with open('alpha.txt', 'w') as file_3:
file_3.write(newlines)
def appendB():
with open('alpha.txt', 'a') as file_2:
file_2.write("\n")
file_2.write(crop + ' ')
file_2.write(quantity + ' ')
crop = input("Which crop? ")
quantity = input("How many? ")
with open('alpha.txt', 'a') as file_0:
if crop in open('alpha.txt').read():
appendA()
else:
appendB()

How to convert from saving to a text file to saving to an excel file in python using csv

I have been programming a maths quiz and have been saving my answer to a text file however now I would like to save these to a excel file in and I have been told I would need to import cvs and use this. I have try to do this but then i have received copious amounts of error. Any answer would would much appreciated. I feel the code I have now is fairly easy to understand and is user friendly.
class_number = prompt_int_big("Before your score is saved ,are you in class 1, 2 or 3? Press the matching number")
filename = (str(class_number) + "csv")
with open(filename, 'a') as f:
f.write("\n" + str(name) + " scored " + str(score) + " on difficulty level " + str(level_of_difficulty) + "\n")
with open(filename) as f:
lines = [line for line in f if line.strip()]
lines.sort()
if prompt_bool("Do you wish to view previous results for your class"):
for line in lines:
print (line)
else:
sys.exit("Thanks for taking part in the quiz, your teacher should discuss your score with you later")

Read and write to a list of names and scores - python

I am trying to create a program that gives the user a short quiz and create a score, which I have done, then I would like to add them to a list in a .txt file. In the program I will ask them their name, so say I have a list such as this;
Bob,7
Bill,5
Jane,6
and someone takes the quiz and inputs the name Bob and gets a score 4 the list will update to;
Bob,4
Bill,5
Jane,6
or someone new takes a quiz, Sarah it will change to;
Bob,4
Bill,5
Jane,6
Sarah,7
So far I have;
import random
file = open("scores.txt", "r")
UserScore=random.randint(0,10)
lines = file.readlines()
file.close()
student=input('What is your name? ')
file = open("scores.txt", "w")
for line in lines:
line = line.strip()
name, score = line.strip().split(",")
if name!=student:
file.write(line)
else:
file.write(name +',' +str(UserScore))
I've randomised the score for now to make it easier to read, however that will be from what the user answered correctly, and I thought this code would read the file then check each name from each line and if the name they entered is the same to the name in the list the line will be replaced with the name and score. However, the file just ends up blank, what am I doing wrong?
Here is what I think is a better idea using the Python pickle module:
In [1]: import pickle
In [2]: scores={'Bob':75, 'Angie':60, 'Anita':80} #create a dict called scores
In [3]: pickle.dump(scores,open('scores.dat','wb')) #dump the pickled object into the file
In [4]: !ls scores.dat #verify that the file has been created
scores.dat
In [5]: !cat scores.dat #list out the file
(dp0
S'Bob'
p1
I75
sS'Angie'
p2
I60
sS'Anita'
p3
I80
s.
In [9]: tscores = pickle.load(open('scores.dat','rb')) #Verification: load the pickled object from the file into a new dict
In [10]: tscores #Verification: list out the new dict
Out[10]: {'Angie': 60, 'Anita': 80, 'Bob': 75}
In [11]: scores == tscores #Verify that the dict object is equivalent to the newly created dict object
Out[11]: True
I tried your code and the first time you run it, then you rewrite the file in one single line. So the next time you run the script on this single line file, you get an unpack exception in the split function and hence you write nothing to the file, resulting in an empty file.
A solution could be to add the newline char again when writing the lines to the file.
import random
file = open("scores.txt", "r")
UserScore=random.randint(0,10)
lines = file.readlines()
file.close()
student=input('What is your name? ')
file = open("scores.txt", "w")
for line in lines:
line = line.strip()
name, score = line.strip().split(",")
if name!=student:
file.write(line + '\n')
else:
file.write(name +',' +str(UserScore) + '\n')
This should do what you want
import random
file = open("scores.txt", "r")
UserScore=random.randint(0,10)
lines = file.readlines()
file.close()
student=input('What is your name? ')
flag = True
file = open("scores.txt", "w")
for line in lines:
line = line.strip()
name, score = line.strip().split(",")
if name!=student:
file.write(line + '\n')
else:
file.write(name +',' +str(UserScore) + '\n')
flag = False
if flag:
file.write(student +',' +str(UserScore) + '\n')
I adjusted a bit of your code and took the liberty to remove the random part and name, score part. But I got some working code. I assume you can make it work for your situation.
file = open("scores.txt", "r+")
lines = file.readlines()
file.close()
us = 15
student = input('What is your name? ')
ls = []
file = open("scores.txt", "r+")
found_student = False
for line in lines:
line = line.strip()
ls = line.split(",")
print("Parsing: " + str(ls))
if not line:
print("Empty line")
pass
elif ls[0] != student:
file.write(line + "\n")
else:
found_student = True
file.write(ls[0] + ',' + str(us) + "\n")
if not found_student:
file.write(student + ',' + str(us) + "\n" )
file.close()

Categories

Resources