Python - Outputting Variables To TXT file - python

Working on outputting text and variables to a .txt file through python. And it doesn't work.
f=open("Output.txt", "a")
f.write("Number Plate:", np ,"\n")
f.write("Valid:", valid ,"\n")
f.write("Speed:", speed ,"\n")
f.write("Ticket:", ticket ,"\n")
f.wrtie("Ticket Price:", ticketprice ,"\n")
f.write("\n")
f.close()
This is the error that is given when i run it.
f.write("Number Plate:", np ,"\n")
TypeError: write() takes exactly one argument (3 given)
Any help is greatly appreciated

Try using str.format.
Ex:
f=open("Output.txt", "a")
f.write("Number Plate: {0}".format(np))
f.write("Valid: {0}".format(valid ))
f.write("Speed: {0}".format(speed ))
f.write("Ticket: {0}".format(ticket ))
f.write("Ticket Price: {0}".format(ticketprice ))
f.write("\n")
f.close()
Note: f.write takes only a single argument, You are trying to pass 3("Number Plate:", np ,"\n")

You can try like this:
with open("Output.txt", "a") as f:
f.write("Number Plate:" + str(np) + "\n")
f.write("Valid:" + str(valid) + "\n")
f.write("Speed:" + str(speed) + "\n")
f.write("Ticket:" + str(ticket) + "\n")
f.write("Ticket Price:" + str(ticketprice) + "\n")
f.write("\n")
Explanation:
If you use with open.... there is no need to explicitly specify the f.close(). And also in f.write() using string concatenation + you can get the required one.

You can simply use str() function
The str() function is meant to return representations of values which
are fairly human-readable.
And your valid code will be like-
f=open("Output.txt", "a")
f.write("Number Plate:" + str(np) + "\n")
f.write("Valid:" + str(valid) + "\n")
f.write("Speed:" + str(speed) + "\n")
f.write("Ticket:" + str(ticket) + "\n")
f.wrtie("Ticket Price:" + str(ticketprice) + "\n")
f.write("\n")
f.close()
your code giving Error, TypeError: write() takes exactly one argument (3 given)
because-
write() method takes only 1 argument, but you are providing 3 argument
1) "Number Plate:" , 2) np and 3) "\n"

Related

How to solve the error while saving a dataframe to csv in python?

I was saving the dataframe as below
Target1_file.to_csv( r'C:\Users\para\PycharmProjects\pythonProject1\Data\data1\'+str(File_T1_name)+'.csv', index=True,header=True)
where
File_T1_name = str(time_.tm_mday) + str(time_.tm_mon) + str(time_.tm_year) + "_SQ12_TC12." + str(filter_index) + "T1_statistics"
I am getting following error:
Missing closing quote [']
',' or ')' expected
how to solve this error?
One thing you could tryout is adding ".csv" to file name variable itself
File_T1_name = str(time_.tm_mday) + str(time_.tm_mon) + str(time_.tm_year) + "_SQ12_TC12." + str(filter_index) + "T1_statistics" + ".csv"
and then use "\\"(double backslash) in the file path instead of "\"(single backslash)
Target1_file.to_csv('C:\\Users\\para\\PycharmProjects\\pythonProject1\\Data\data1\\' + str(File_T1_name), index=True, header=True)
Use f-strings instead of raw strings:
Target1_file.to_csv(fr"C:\Users\para\PycharmProjects\pythonProject1\Data\data1\{File_T1_name}.csv", index=True,header=True)
where
File_T1_name = fr"{time_.tm_mday}{time_.tm_mon}{time_.tm_year}_SQ12_TC12.{filter_index}T1_statistics"

Remove string from text file after print (python)

I have the following code that pulls a list from a txt file and then prints one line at a time. The problem I am having is that I want the code to remove that line from the txt file after it has printed it.
I have tried using a few different methods I found online but had no success on maiking it work.
Would any have any idea's on how to achive this?
import time
from time import sleep
import random
my_file=open('testlist.txt','r')
file_lines=my_file.readlines()
my_file.close()
for line in file_lines:
try:
sep = line.split(":")
select_list = ["test " + sep[0] + "? " + sep[1], "test " + sep[0] + "! " + sep[1], "test " + sep[0] + "? " + sep[1]]
print(random.choice(select_list))
sleep(1)
except Exception as e:
print(e)
Basically after the "print(random.choice(select_list))", we would want to delete "line" from "testlist.txt".
Let's go through some logic and see how to achieve the results you are expecting.
Humanly / Intuitively, the actions are
1. Read files line-by-line to memory
my_file=open('testlist.txt','r')
file_lines=my_file.readlines()
my_file.close()
It would be a better practice to consider using with context managers (it will automatically help you close the file one you are out of the indentation from the with scope, i.e.
with open('testlist.txt','r') as my_file:
file_lines = my_file.readlines()
2. For each line that is read, (a) split it by : character, (b) perform a few string operations and (c) randomly select one of the output from (2b), i.e
for line in file_lines:
sep = line.split(":")
select_list = ["test " + sep[0] + "? " + sep[1], "test " + sep[0] + "! " + sep[1], "test " + sep[0] + "? " + sep[1]]
print(random.choice(select_list))
2b. Now, lets take a look at (2b) and see what we are trying to achieve, i.e.
select_list = ["test " + sep[0] + "? " + sep[1], "test " + sep[0] + "! " + sep[1], "test " + sep[0] + "? " + sep[1]]
We produce 3 items in the select_list, where it seems the "test " + sep[0] + "? " + sep[1] has 2 occurence and the "test " + sep[0] + "! " + sep[1] is included once.
"test " + sep[0] + "? " + sep[1]
"test " + sep[0] + "! " + sep[1]
"test " + sep[0] + "? " + sep[1]
in any case, the select_list = [ ... ] is a valid line of code.
2c. Regarding the print(random.choice(select_list)) line, it doesn't affect any variables and it's just randomly choosing an item from the select_list
Going back to original question,
I want the code to remove that line from the txt file after it has printed it.
Q: Would this mean removing the line from the original file_lines in open('testlist.txt','r')?
A: If so, then it would be removing all lines from the original testlist.txt, because if everything would checks out for step 2b and 2c (in the try part of the code).
But if step 2b or 2c throws an error and get caught in the except, then it would be a line that you won't want to throw out (as per your original question).
In that case, it looks like what you want to get eventually is a list of lines that falls into the except scope of the code.
If so, then you would be looking at something like this:
# Reading the original file.
with open('testlist.txt','r') as my_file:
# Opening a file to write the lines that falls into the exception
with open('testlist-exceptions.txt', 'w') as fout:
# Iterate through the original file line by line.
for line in my_file:
# Step 2a.
sep = line.split(":")
# Supposedly step 2b, but since this is the only
# point of the code that can throw an exception
# most probably because there's no sep[1],
# you should instead check the length of the sep variable.
if len(sep) < 2: # i.e. does not have sep[1].
# Write to file.
fout.write(line)
else: # Otherwise, perform the step 2b.
select_list = ["test " + sep[0] + "? " + sep[1], "test " + sep[0] + "! " + sep[1], "test " + sep[0] + "? " + sep[1]]
print(random.choice(select_list))
Now the new logic is a lot simpler than the intuition based logic you have in the original code but achieves the same output that you are expecting.
The new logic is as such:
Open the original file for reading, open another file to write the file that I expect
Read the file line by line
Split the file by :
Check if it allows the string operation to join the sep[0] and sep[1]
if yes, perform the string operation to create select_list and choose one of the item in select_list to print to console
if no, print out that line to the output file.
If for some reason, you really want to work with the file in place with Python, then take a look at Is it possible to modify lines in a file in-place?
And if you really need to reduce memory footprint and want something that can edit lines of the file in-place, then you would have to dig a little into file seek function https://docs.python.org/3/tutorial/inputoutput.html#methods-of-file-objects
Some unsolicited Python suggestions (hope this helps)
When you need to delete something from file, if disk space allows, don't delete it, create another file with the expected output without the deleted lines.
Whenever possible, try to treat files that you want to read as immutable, and less like Perl-style in-place files that allows edits
It's tempting to do try-excepts when you just want something to work, but catch-all excepts are hard to debug and normally shows that the logic of the steps can be better. https://docs.python.org/3/tutorial/errors.html#handling-exceptions
I would give you example but better try to follow this guide there is various ways , first issue is opening the file with 'r' mode
Deleting lines

could not convert string to float "price"

when I run the program this has been popping up. could not convert string to float. I tried to look it up but I couldn't find anything.
here's the code:
f = open("ticket.txt",'r')
s=f.read()
lines=s.split("\n")
priceMax=0
priceMin=9999
total=0
for line in lines:
cols=line.split(" ")
price=(float)(cols[1])
total=total+price
if(price>priceMax):
priceMax=price
if(price<priceMin):
priceMin=price
f.close()
f=open("output.txt",'w')
f.write("*******************************************\n")
f.write(" TICKET REPORT\n")
f.write("*******************************************\n\n")
f.write("There are " + str(len(lines)) + " tickets in the database.\n\n")
f.write("Maximum Ticket price is $" + str(priceMax) + "\n")
f.write("Minimum Ticket price is $" + str(priceMin) + "\n")
f.write("Average Ticket price is $" + str(total / len(lines)) + "\n\n")
f.write("Thank you for using our ticket system!\n\n")
f.write("*******************************************\n")
f.close()
print("File Created sucessfully")
Yeah, indentation is important in Python. You must be consistent.
This "cast" (float) evaluates to, basically, the float() function, and then you call it, so that's not the problem. More canonical is f = float("123.45"). Now, this will throw a ValueError exception if there's an invalid number passed, so, you might want to catch this, so you can find out where the problem is. Along the lines of:
s = "123.baboom"
try:
f = float(s)
except ValueError as e:
print("Oh, no, got an exception:", e)
print("The offending string was: ", s)
What's the error that's shown?
I think the issue is that you have started the list with cols[1] instead of cols[0].
Also the indentation is wrong here.
for line in lines:
cols=line.split(" ")
price=(float)(cols[0])
total=total+price
if(price>priceMax):
priceMax=price
if(price<priceMin):
priceMin=price

argument of type 'int' is not iterable Issue

What I trying to do is picking random integers from a value, for example: 1:32 will be an input, I will split by the : and then select a random value. Then Selenium will select the dropdown based on what value is returned.
My code:
# SELECT
if register_parts[3] == "SELECT":
if register_parts[0] + '="' + register_parts[1] + '"' in self.driver.page_source:
_select_value = ""
if ":" in register_parts[2]:
_select_value = self.get_random_value_between(register_parts[2])
_select = Select(selenium_action)
_select.select_by_visible_text(_select_value)
self.write_to_debug_file("self.select_by_visible_text(" + _select_value + ") --> SELECT --> [ " + _select_value + " ]")
else:
_select_value = register_parts[2]
_select = Select(selenium_action)
_select.select_by_visible_text(_select_value)
self.write_to_debug_file("self.select_by_visible_text(" + _select_value + ") --> SELECT --> [ " + _select_value + " ]")
Additional function:
def get_random_value_between(self, input_values):
''' this function will return a random value between: x:x or 1:31 for example ... '''
parts = input_values.split(':')
return random.randrange(int(parts[0]), int(parts[1]))
The problem is on this line:
_select.select_by_visible_text(_select_value)
I'm getting the error:
argument of type 'int' is not iterable
From reading up, I think the issue lies in the fact I am doing:
if ":" in
I could be wrong. I'm not sure how to fix it. Any help on the issue would be appreciated. As far as I can see, the code should work, but I must be missing something. I have read a few threads on here regarding the error but it's still not sinking totally in.
If possible, cast _select_value as string before using _select.select_by_visible_text.
And recast as int values after the iteration.
I think this is correct. If the error is on if and not the else, then your passing an Int as an argument to a method that needs a text/str value.
Just try the following line:
_select.select_by_visible_text(str(_select_value))

How can I export my quiz results to a csv file using python 3? [duplicate]

This question already has answers here:
How can I concatenate str and int objects?
(1 answer)
String formatting: % vs. .format vs. f-string literal
(16 answers)
Closed 8 years ago.
I want the results to be in the format Date, Question, Name and Score
file = open("results.csv", "a")
file.write('Date, Question, Name, Score\n' + date + ',' question + ',' + name + ',' + score + '\n')
file.close()
When I run this code i keep getting the error: TypeError: Can't convert 'int' object to str implicitly
You have to cast to any ints to string string before you can concat it to another and write to file.
str(score) # <-
file.write('Date, Question, Name, Score\n' + date + ',' question + ',' + name + ',' + str(score) + '\n')
Or use str.format:
with open("results.csv", "a") as f: # with closes your files automatically
f.write('Date, Question, Name, Score\n {}, {}, {}, {}'.format(date, question, name ,score))
You may also find the csv module useful
Then convert it explicitly to str:
file.write('Date, Question, Name, Score\n' + str(date) + ',' question + ',' + name + ',' + str(score) + '\n')

Categories

Resources