Removing a line from a file - python-3.x

I have a file named (data.txt):
243521,Biscuit,Flour:Cream,89.5,9,1
367534,Bread,Flour,67.3,1,2
463254,Chocolate,Cocoa butter:Sugar:Milk powder,45.6,4,0
120014,Buns,Wheat Flour,24.9,5,2
560214,Cake,Flour:Baking Powder:Cake Mix,70.5,3,1
123456,burger,bread crumbs:beef:tomato,99.9,10,0
The numbers after the last comma is sold items. I want to write a code that can delete a line just if the number after the last comma is 0. This is the code I wrote but it removes the line even if the number after the last comma is not zero :
productID=input("")
with open("data.txt","r+") as file:
lines= file.readlines()
file.seek(0)
for line in lines:
productInfo= line.split(",")
y=0
if productInfo[5]>"0":
if y==0:
print("Product cannot be removed: sold items must be 0")
y=1
elif productID not in line:
file.write(line)
file.truncate()
print("Product is removed successfully")

I regret that I do not understand what you are asking for. If you have trouble expressing a difficult question, try asking the question to a friend, and then write down what you say.
Other than the noise that y introduces for no reason, the other odd thing about this code is this comparison:
productInfo[5]>"0"
Probably that comparison does not do what you expect.
I believe you just want to know if the last token is a "0" or not. For this it is better to test for equality or inequality, instead of attempting to perform a value comparison of two strings.
String equality can be tested with ==. Check for inequality with !=.
I believe you want this:
productInfo[5] != "0"

From what I have understood, you have a file that contains comma-separated data and last value is of your interest. If that value is 0, you want to remove that line.
General idea is to read the lines in file and split the , in line and access last item. Your mistake is, as many have pointed out, you are trying to compare strings with > which is not valid in python. Following code works for me with your sample data:
#reading the lines in data as list
with open("data.txt", "r") as f:
lines = f.readlines()
new_array = []
#empty array so we can populate it with lines that don't have a 0 at the end
user_input = input("Enter a number: ") #Capturing user input
for line in lines: #iterating over all lines
line = line.split(",") #splitting , in line
if line[len(line)-1].strip() != "0" and line[0] != user_input:
#if first item and last item are not user input and 0 respectively
new_array.append(",".join(line))
elif line[len(line)-1].strip() == "0" and line[0] != user_input:
#if last item is 0 but first item is not user input
new_array.append(",".join(line))
else:
print("ignoring:", *line)
with open("data2.txt", "w") as f: #creating new data file without 0
f.writelines(new_array) #writing new array to new datafile
#data2.txt now contains only lines that have no 0 at the end

Related

Find, multiply and replace numbers in strings, by line

I'm scaling the Gcode for my CNC laser power output. The laser's "S" value maxes at 225 and the current file scale is 1000. I need to multiply only/all S values by .225, omit S values of 0, and replace in the string for each line. There are pre-designated "M", "G", "X", "Y", "Z", "F", and "S" in the Gcode for axis movement and machine functions.
Note: I can't do this manually as there's like 7.5k lines of code.
Hoping for .py with an outcome like (top 3 lines):
Old> G1Y0.1S0 New> G1Y0.1S0
Old> G1X0.1S248 New> G1X0.1S55.8
Old> G1X0.1S795.3 New> G1X0.1S178.9
Example file Code:
G1Y0.1S0
G1X0.1S248
G1X0.1S795.3
G1X0.2S909.4
G1X0.1S874
G1X0.1S374
G1X1.1S0
G1X0.1S610.2
G1X0.1S893.7
G1X0.6S909.4
G1X0.1S893.7
G1X0.1S661.4
G1X0.1S157.5
G1X0.1Y0.1S0
G1X-0.1S66.9
G1X-0.1S539.4
G1X-0.2S909.4
G1X-0.1S897.6
G1X-0.1S811
G1X-0.1S515.7
G1X-0.1S633.9
G1X-0.1S874
G1X-0.3S909.4
G1X-0.1S326.8
G1X-0.8S0
Tried this:
import os
import sys
import fileinput
print("Text to Search For:")
textToSearch = input("> ")
print("Set Max Power Output:")
valueMult = input("> ")
print("File to work:")
fileToWork = input("> ")
tempFile = open(fileToWork, 'r+')
sValue = int
for line in fileinput.input (fileToWork):
if textToSearch in line:
c = str(textToSearch,(sValue)) #This is where I'm stuck.
print("Match Found >> ", sValue)
else:
print("Match Not Found")
tempFile.write(line.replace(textToSearch, (sValue,"(sValue * (int(valueMult)/1000))")))
tempFile.close()
#input("\n\n Press Enter to Exit")
Output:
Text to Search For:
> S
Set Max Power Output:
> 225
File to work:
> test.rtf
Match Not Found
Traceback (most recent call last):
File "/Users/iamme/Desktop/ConvertGcode.py", line 25, in <module>
tempFile.write(line.replace(textToSearch, (sValue,"(sValue * (int(valueMult)/1000))")))
TypeError: replace() argument 2 must be str, not tuple
>>>
test.rtf file:
Hello World
X-095Y15S434.5
That is Solid!
Your code has a couple of issues that need to be addressed:
first, you declare the sValue variable but never assign it the value from every line in your loop,
second, said variable is an int, but should be a float or you'll lose the decimal part seen in the file,
and third, since you're not getting the corresponding values, you're not multiplying the aforementioned values by the new scale factor to then replace the old with this.
Additionally, you're opening the original file in read/write mode (r+), but I would recommend you write to a new file instead.
Now, here is your code with fixes and changes (I'm taking the liberty to write variable names in Python style):
multiplier = input("New max power output for S: ")
input_file = input("Input file: ")
output_file = input("Output file: ")
with open(input_file, 'r') as source, open(output_file, 'w') as target:
for line in source:
if 'S' in line:
line = line.removesuffix('\n')
split_line = line.split('S', -1)
new_value = float(split_line[1]) * float(multiplier)
new_line = f'{split_line[0]}S{new_value:.1f}\n'
print(f'Old> {line:25s}New> {new_line}', end='')
target.write(new_line)
else:
target.write(line)
As you can see, we open both source and target files at the same time. By using the with statement, the files are closed at the end of that block.
The code assumes the text to search will appear no more than once per line.
When a match is found, we need to remove the newline from the line (\n) so it's easy to work with the number after the S. We split the line in two parts (stored in the list split_line), and convert the second element (S's value) to a float and multiply it by the entered multiplier. Then we construct the new line with its new value, print the old and new lines, and write it to the target file. We also write the line to the target file when a match isn't found so we don't lose them.
IMPORTANT: this code also assumes no additional values appear after S{value} in the lines, as per your sample. If that is not the case, this code will fail when reaching those lines.

Find items in a text file that is a incantinated string of capitalized words that begin with a certain capital letter in python

I am trying to pull a string of input names that get saved to a text file. I need to pull them by capital letter which is input. I.E. the saved text file contains names DanielDanClark, and I need to pull the names that begin with D. I am stuck at this part
for i in range(num):
print("Name",i+1," >> Enter the name:")
n=input("")
names+=n
file=open("names.txt","w")
file.write(names)
lookUp=input("Did you want to look up any names?(Y/N)")
x= ord(lookUp)
if x == 110 or x == 78:
quit()
else:
letter=input("Enter the first letter of the names you want to look up in uppercase:")
file=open("names.txt","r")
fileNames=[]
file.list()
for letter in file:
fileNames.index(letter)
fileNames.close()
I know that the last 4 lines are probably way wrong. It is what I tried in my last failed attempt
Lets break down your code block by block
num = 5
names = ""
for i in range(num)
print("Name",i+1," >> Enter the name:")
n=input("")
names+=n
I took the liberty of giving num a value of 5, and names a value of "", just so the code will run. This block has no problems. And will create a string called names with all the input taken. You might consider putting a delimiter in, which makes it more easier to read back your data. A suggestion would be to use \n which is a line break, so when you get to writing the file, you actually have one name on each line, example:
num = 5
names = ""
for i in range(num)
print("Name",i+1," >> Enter the name:")
n = input()
names += n + "\n"
Now you are going to write the file:
file=open("names.txt","w")
file.write(names)
In this block you forget to close the file, and a better way is to fully specify the pathname of the file, example:
file = open(r"c:\somedir\somesubdir\names.txt","w")
file.write(names)
file.close()
or even better using with:
with open(r"c:\somedir\somesubdir\names.txt","w") as openfile:
openfile.write(names)
The following block you are asking if the user want to lookup a name, and then exit:
lookUp=input("Did you want to look up any names?(Y/N)")
x= ord(lookUp)
if x == 110 or x == 78:
quit()
First thing is that you are using quit() which should not be used in production code, see answers here you really should use sys.exit() which means you need to import the sys module. You then proceed to get the numeric value of the answer being either N or n and you check this in a if statement. You do not have to do ord() you can use a string comparisson directly in your if statement. Example:
lookup = input("Did you want to look up any names?(Y/N)")
if lookup.lower() == "n":
sys.exit()
Then you proceed to lookup the requested data, in the else: block of previous if statement:
else:
letter=input("Enter the first letter of the names you want to look up in uppercase:")
file=open("names.txt","r")
fileNames=[]
file.list()
for letter in file:
fileNames.index(letter)
fileNames.close()
This is not really working properly either, so this is where the delimiter \n is coming in handy. When a text file is opened, you can use a for line in file block to enumerate through the file line by line, and with \n delimiter added in your first block, each line is a name. You also go wrong in the for letter in file block, it does not do what you think it should be doing. It actually returns each letter in the file, regardless of whay you type in the input earlier. Here is a working example:
letter = input("Enter the first letter of the names you want to look up in uppercase:")
result = []
with open(r"c:\somedir\somesubdir\names.txt", "r") as openfile:
for line in openfile: ## loop thru the file line by line
line = line.strip('\n') ## get rid of the delimiter
if line[0].lower() == letter.lower(): ## compare the first (zero) character of the line
result.append(line) ## append to result
print(result) ## do something with the result
Putting it all together:
import sys
num = 5
names = ""
for i in range(num)
print("Name",i+1," >> Enter the name:")
n = input("")
names += n + "\n"
with open(r"c:\somedir\somesubdir\names.txt","w") as openfile:
openfile.write(names)
lookup = input("Did you want to look up any names?(Y/N)")
if lookup.lower() == "n":
sys.exit()
letter = input("Enter the first letter of the names you want to look up in uppercase:")
result = []
with open(r"c:\somedir\somesubdir\names.txt", "r") as openfile:
for line in openfile:
line = line.strip('\n')
if line[0].lower() == letter.lower():
result.append(line)
print(result)
One caveat I like to point out, when you create the file, you open the file in w mode, which will create a new file every time, therefore overwriting the a previous file. If you like to append to a file, you need to open it in a mode, which will append to an existing file, or create a new file when the file does not exist.

Why, when I sort a list of 13 numbers, does python only return the last number?

I have a list of first name, last name, and score in a text file that refers to a student and their test score. When I go to sort them so I can find the median score, it only returns from the sort() the last grade on the list. I need it to return all of them, but obviously sorted in order. Here is the part of my code in question:
def main():
#open file in read mode
gradeFile = open("grades.txt","r")
#read the column names and assign them to line1 variable
line1 = gradeFile.readline()
#tell it to look at lines 2 to the end
lines = gradeFile.readlines()
#seperate the list of lines into seperate lines
for line in lines:
#initialize grades list as an empty list
gradeList = []
#iterate through each line and take off the \n
line = line.rstrip()
line = line.split(",")
grades = line[-1]
try:
gradeList.append(float(grades))
except ValueError:
pass
#print(gradeList)
#sort the grades
gradeList.sort(reverse=False)
print(gradeList)
You clear the list each time the loop runs. Move the assignment outside the loop.

Trying to get my python script to see if the text file reads only numbers or words

userinput = raw_input('Write file name:')
myfile = open(userinput)
content = myfile.read()
if content == "":
print("Empty file")
elif content.isalpha():
print("Just letters")
elif content.isdigit():
print("Numbers")
else:
print("It's both")
-When I do this and write text file that only have numbers I always get It's both and I don't know what to change. Also if anyone could help my when the script has found if the file only contains letters or number I need to find mean,median,min,max and standard deviation for the numbers how should I do that?
THANKS!
You are not accounting for newlines or spaces:
In [65]: "abc\n".isalpha()
Out[65]: False
In [66]: "133\n".isdigit()
Out[66]: False
In [67]: "133 123".isdigit()
Out[67]: False
If the data is a single line with no spaces use content.rstrip():
In [70]: "abc\n".rstrip().isalpha()
Out[70]: True
If there are space then you will have to decide what you consider alpha or all digits, you can split and rejoin into a string without spaces or use str.translate to replace various whitespace with an empty string.
Another option is to use all with str.isspace:
In [72]: content = "123 123\n"
In [73]: all(ch.isdigit() or ch.isspace() for ch in content)
Out[73]: True
In [74]: content = "foo\nbar\n"
In [75]: all(ch.isalpha() or ch.isspace() for ch in content)
Out[75]: True
what you choose completely depends on what you consider qualifies as being either alpha or all digits i.e do multiple lines separated by newlines and /or whitespace qualify or does only consecutive characters on a single line with no whitespace. Either way you will have to remove any trailing newlines or you will always reach your else.
If you are going down the all route or to work for very large files we can do it without reading all the file into memory:
import os
def check_type(user_input):
if os.stat(user_input ).st_size == 0:
return "Empty file"
with open(user_input) as my_file:
if all(ch.isdigit() or ch.isspace() for line in my_file for ch in line):
return "digits!"
my_file.seek(0)
if all(ch.isdigit() or ch.isspace() for line in my_file for ch in line):
return "Alpha"
return "Both"
Then to check if the file is all digits and calculate the average:
from collections import Counter
user_input = raw_input('Write file name:')
if check_type(user_input) == "Digits":
with open(user_input) as f:
nums = Counter(float(n) for line in f for n in line.split())
print("Average = {}".format(sum(k*v for k,v in nums.items()) / sum(nums.values())))
The std dev and median I will leave for your self to figure out.

text file reading and writing, ValueError: need more than 1 value to unpack

I need to make a program in a single def that opens a text file 'grades' where first, last and grade are separated by comas. Each line is a separate student. Then it displays students and grades as well as class average. Then goes on to add another student and grade and saves it to the text file while including the old students.
I guess I just don't understand the way python goes through the text file. If i comment out 'lines' I see it prints the old_names but its as if everything is gone after. When lines is not commented out 'old_names' is not printed which makes me think the file is closed? or empty? however everything is still in the txt file as it should be.
currently i get this error.... Which I am pretty sure is telling me I'm retarded there's no information in 'line'
File "D:\Dropbox\Dropbox\1Python\Batch Processinga\grades.py", line 45, in main
first_name[i], last_name[i], grades[i] = line.split(',')
ValueError: need more than 1 value to unpack
End goal is to get it to give me the current student names and grades, average. Then add one student, save that student and grade to file. Then be able to pull the file back up with all the students including the new one and do it all over again.
I apologize for being a nub.
def main():
#Declare variables
#List of strings: first_name, last_name
first_name = []
last_name = []
#List of floats: grades
grades = []
#Float grade_avg, new_grade
grade_avg = new_grade = 0.0
#string new_student
new_student = ''
#Intro
print("Program displays information from a text file to")
print("display student first name, last name, grade and")
print("class average then allows user to enter another")
print("student.\t")
#Open file “grades.txt” for reading
infile = open("grades.txt","r")
lines = infile.readlines()
old_names = infile.read()
print(old_names)
#Write for loop for each line creating a list
for i in len(lines):
#read in line
line = infile.readline()
#Split data
first_name[i], last_name[i], grades[i] = line.split(',')
#convert grades to floats
grades[i] = float(grades[i])
print(first_name, last_name, grades)
#close the file
infile.close()
#perform calculations for average
grade_avg = float(sum(grades)/len(grades))
#display results
print("Name\t\t Grade")
print("----------------------")
for n in range(5):
print(first_name[n], last_name[n], "\t", grades[n])
print('')
print('Average Grade:\t% 0.1f'%grade_avg)
#Prompt user for input of new student and grade
new_student = input('Please enter the First and Last name of new student:\n').title()
new_grade = eval(input("Please enter {}'s grade:".format(new_student)))
#Write new student and grade to grades.txt in same format as other records
new_student = new_student.split()
new_student = str(new_student[1] + ',' + new_student[0] + ',' + str(new_grade))
outfile = open("grades.txt","w")
print(old_names, new_student ,file=outfile)
outfile.close()enter code here
File objects in Python have a "file pointer", which keeps track of what data you've already read from the file. It uses this to know where to start looking when you call read or readline or readlines. Calling readlines moves the file pointer all the way to the end of the file; subsequent read calls will return an empty string. This explains why you're getting a ValueError on the line.split(',') line. line is an empty string, so line.split(",") returns a list of length 0, but you need a list of length 3 to do the triple assignment you're attempting.
Once you get the lines list, you don't need to interact with the infile object any more. You already have all the lines; you may as well simply iterate through them directly.
#Write for loop for each line creating a list
for line in lines:
columns = line.split(",")
first_name.append(columns[0])
last_name.append(columns[1])
grades.append(float(columns[2]))
Note that I'm using append instead of listName[i] = whatever. This is necessary because Python lists will not automatically resize themselves when you try to assign to an index that doesn't exist yet; you'll just get an IndexError. append, on the other hand, will resize the list as desired.

Resources