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")
I am trying to remove multiple lines from a file where the lines begin with a specified string.
I've tried using a list as below but the lines are written to the file the number of times equal to the items in the list. Some of the lines are removed some are not I'm pretty sure that it is due to not reading the next line at the correct time
trunklog = open('TrunkCleanedDaily.csv', 'r')
fh = open("TCDailyFinal.csv", "w")
firstletter = ['Queue,Completed', 'Outbound,', 'Red_Team_DM,', 'Sunshine,', 'Agent,','Disposition,', 'Unknown,']
while True:
line = trunklog.readline()
if not line:
break;
for i in firstletter:
if line.startswith(i):
print('del ' + line, end='')
# line = trunklog.readline()
else:
fh.write(line)
print('keep ' + line,end='')
line = trunklog.readline()
Any help setting me straight about this is appreciated.
Some of the content I am trying to remove:
Queue,Completed,Abandons,Exits,Unique,Completed %,Not Completed %,Total Calls,
Green_Team_AMOne,93,0,0,0,100.00%,0.00%,8.04%,
Green_Team_DM,11,0,0,0,100.00%,0.00%,0.95%,
Green_Team_IVR,19,0,0,0,100.00%,0.00%,1.64%,
Outbound,846,131,0,0,86.59%,13.41%,84.44%,
Red_Team_AMOne,45,0,0,0,100.00%,0.00%,3.89%,
Red_Team_DM,3,0,0,0,100.00%,0.00%,0.26%,
Red_Team_IVR,5,0,0,0,100.00%,0.00%,0.43%,
Sunshine,4,0,0,0,100.00%,0.00%,0.35%,
Queue,Total Call Time,Average Call Time,Average Hold Time,Call Time %,None,
Green_Team_AMOne,32:29:06,20:57,00:10,42.92%,None,
Green_Team_DM,2:41:35,14:41,00:16,3.56%,None,
Green_Team_IVR,1:47:12,05:38,00:19,2.36%,None,
Try below code:
trunklog = open('TrunkCleanedDaily.csv', 'r')
fh = open("TCDailyFinal.csv", "w")
firstletter = ['Queue,Completed', 'Outbound,', 'Red_Team_DM,', 'Sunshine,', 'Agent,', 'Disposition,', 'Unknown,']
for line in trunklog:
cnt=0
for i in firstletter:
if line.startswith(i):
print('del ' + line, end='')
cnt=1
if not cnt:
fh.write(line)
print('keep ' + line, end='')
I have modified your code a little bit.
And added a variable 'cnt', which will be 1, if first word is in firstletter list.
If cnt=0, then it will write line to the new file.
You just have to left intend else statement for for loop and add break if you have to delete a line.
trunklog = open('TrunkCleanedDaily.csv', 'r')
fh = open("TCDailyFinal.csv", "w")
firstletter = ['Queue,Completed', 'Outbound,', 'Red_Team_DM,', 'Sunshine,', 'Agent,','Disposition,', 'Unknown,']
while True:
line = trunklog.readline()
if not line:
break;
for i in firstletter:
if line.startswith(i):
print('del ' + line, end='')
break
else:
fh.write(line)
print('keep ' + line,end='')
Output file
Green_Team_AMOne,93,0,0,0,100.00%,0.00%,8.04%,
Green_Team_DM,11,0,0,0,100.00%,0.00%,0.95%,
Green_Team_IVR,19,0,0,0,100.00%,0.00%,1.64%,
Red_Team_AMOne,45,0,0,0,100.00%,0.00%,3.89%,
Red_Team_IVR,5,0,0,0,100.00%,0.00%,0.43%,
Queue,Total Call Time,Average Call Time,Average Hold Time,Call Time %,None,
Green_Team_AMOne,32:29:06,20:57,00:10,42.92%,None,
Green_Team_DM,2:41:35,14:41,00:16,3.56%,None,
Green_Team_IVR,1:47:12,05:38,00:19,2.36%,None,
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.
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()
I want to know the line numbers of a certain file
Following is the code
But the result is not correct:The true file line number == Console result number + 1
is the problem in "open().readlines()" ?
if there are contents in the last line, the result is correct
import os
import os.path
absPath = os.curdir
while True:
print '\nplease select the file you want to know the line nums:'
print os.listdir(absPath)
fileName = raw_input()
absFilePath = absPath + '//' + fileName
if os.path.isfile(absFilePath):
count = len(open(absFilePath).readlines())
print 'the ' + fileName + ' file line nums is>>>' + str(count) + '>>>'
else:
print 'Please check the fileName or the input is not a file'
You shouldn't use readlines() here, as it unnecessarily loads the whole file into memory. The following snippet is more memory-friendly:
with open(filename) as f:
line_count = sum(1 for line in f)
I find the reason:
the notepad++ line num(left side) shows 6,
but open().readlines() return list ['aaa\n','bbb\n','ccc\n','\n','\n']
'\n' will add a new line num in editor,but not add a list num
So if the last line is like 'bbb',the script is correct
if the last is like '\n' ,'\n',the line num must add 1