eval lines from a file - python

I am creating a program that stores options in a txt file, and I tried a few different lines but so far I think an eval is the best one.
I got this info in the file:
colordefondo = "#abcdef"
and I got this eval in the program:
for line in open("filename.txt", "r"):
eval(line)
However, when I try the code it gives me this error:
Traceback (most recent call last):
File "D:\project-sae\Sae.py", line 25, in <module>
eval(line)
File "<string>", line 1
colordefondo = "#abcdef"
^
SyntaxError: invalid syntax
My question is Why? And if anyone knows a better way to load and store the value of several options from a txt file it would be great. Nevertheless my question is about why that eval is failing, my knowledge about how eval works seems wrong and I don't know why, used it several times before, just never from a file.

As the documentation says, 'eval' evaluates an expression. Not a statement. Assignments are statements.
You could use the exec statement. But if you want to exec all of the lines of a file, that's exactly what execfile does. (I'm assuming Python 2.x here; things are a little different in 3.x, but the idea is similar.)
However, this is a bad idea to do in the first place. A better way to load and store the value of several options from a txt file is to use anything other than Python source as your format. JSON, .ini files, .rc files, etc. Python comes with code built-in to handle a variety of such formats. See File Formats and Internet Data Handling for a list of the relevant modules, read through them, and pick the one you want.

Related

why is the error thinking Its not string?

path of file is:
"C:\Users\deana\OneDrive\Marlon's files\Programming\Python\PITT\PITT_LIbrary\Lists\test.txt"
lines of code are:
import os
os.chdir("C:/Users/deana/OneDrive/Marlon's files/Programming/Python/PITT/PITT_LIbrary/Lists")
exec(open('test.txt'))
the error is this:
Traceback (most recent call last):
File "<pyshell#14>", line 1, in <module>
exec(open('test.txt'))
TypeError: exec() arg 1 must be a string, bytes or code object
also if I try on one line as such:
exec(open(r"C:/Users/deana/OneDrive/Marlon's files/Programming/Python/PITT/PITT_LIbrary/Lists/test.txt"))
i'ts the same error. (with and without r)
super frustrationg as it reads like i'm not inputting string... but it is string!?!
also I've done this litteraly the same way before, restarted IDLE shell, no difference.
ugh! I always get stupid errors with file paths.
I should have been using os.startfile() to open this.
It was confusing by using .open(). as I was attempting to open in default app.
before, i've used exec.open() to open .py files and guess I got them confused.
exec is just used to open other scripts... need stronger coffee next time.
Try this:
import os
os.chdir("C:/Users/deana/OneDrive/Marlon's files/Programming/Python/PITT/PITT_LIbrary/Lists")
exec(open('test.txt', 'rb'))
You can convert the txt file to bytes by opening it with rb (read bytes).

Python text command doesn't output the string data on the actual text file

I am just learning about the text file function in python 3 by using website called, https://www.w3schools.com/python/python_file_write.asp and https://www.geeksforgeeks.org/reading-writing-text-files-python/ although the program seems collect, the text data in the python's programming screen doesn't show in the actual text data file.
Is there any mistake I've ever made in the text program below?
The version of my Python is Python 3.7.5 .
File = open("NewTextFile.Txt", "a")
string = "ABC"
File.write(string)
File.close
You forgot to put () at File.close, so the file is not properly closed. Try putting ().
Often it is recommended to use with clause:
with open('NewTextFile.Txt', 'a') as file:
string = 'ABC'
file.write(string)
Note that you don't need to explicitly close the file here. The file is kept open within the clause. Once your python program exits the with clause, the file is automatically closed; in this way your program gets less prone to mistakes.
For more information, see a relevant python doc:
It is good practice to use the with keyword when dealing with file objects. The advantage is that the file is properly closed after its suite finishes, even if an exception is raised at some point.
— https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files

Syntax error when trying to open a file through Python 3 Command Shell

So I am learning Python through Udemy tutorials and now I need to open a file through CMD(CMD is opened on folder I need) and when I am typing function for opening file it says syntax error, but I have made everything good what a guy on tutorials says, I really don't know what what should I do, I checked all of the forums and still cant find the answer.
Here are some screenshots:
Couple of issues:
1.Your text file is called "example.txt.txt" instead of "example.txt"
2.The "example.txt","r" should be surrounded with brackets () instead of <>. These symbols look similar in cmd and are easy to confuse.
#instead of
file = open<"example.txt","r">
#use
file = open("example.txt","r")
This should fix your problem; let me know if it does.
You have to use parenthesss () not <>
file = open("example.txt","r")
check https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files

Python fwrite function error: a bytes like object is required, not str

There is several errors "a bytes-like object is required, not 'str'. But none of them is related to mine. I open the file using open(filename, "w"), not "wb". The code is like 150 lines long. The beginning of the code is to assign the input of command line into parser args.
The args.result is an empty txt file which I want to write my result onto.
I open it using open.
I think the following code should be enough to illustrate my question. Before the line 65, the code is writing two functions to be used in calculation but I think it should be irrelevant to the bug.
In the code, I manually create the file 'save/results/result.txt' in the command terminal. Then I open the file in the line 132.
The remaining code is
A interesting bug happens that the line 158 runs OK. "begin training\n" can be written into file. Then for the line 165, during the first time of loop, it is OK and "aa\n" can be written into file. But during the second loop, the program end with an error "a bytes-like" object is required, not 'str'. The error message is as following.
Anyone could provide a help of that?
Quite thanks.
I've never had trouble with similar code, but if you want a quick fix, I'd bet making a string named f_text and adding to it within the for loop, then writing all of it to the file after the last iteration of the for loop would be a simple way to circumvent the problem.
IE:
f_text = ""
for epoch in range(your_range):
# Do calculations
print(the_stuff_you_wanted_to)
f_text += the_stuff_you_wanted_to + "\n"
f.write(f_text)
I'm mostly posting this to act as a quick fix though. I feel that there's probably a better solution and could help more if you show more of your code, like where you actually initialize f.

Inconsistent file behavior

I'm trying to track down a Python UnicodeDecodeError in the following log line:
10.210.141.123 - - [09/Nov/2011:14:41:04 -0800] "gfR\x15¢\x09ì|Äbk\x0F[×ÐÖà\x11CEÐÌy\x5C¿DÌj\x08Ï ®At\x07å!;f>\x08éPW¤\x1C\x02ö*6+\x5C\x15{,ªIkCRA\x22 xþP9â\x13h\x01­¢è´\x1DzõWiË\x5C\x10sòʨR)¶²\x1F8äl¾¢{ÆNw\x08÷#ï" 400 166 0.000 "-" "-"
I opened the entire log file in Vim, and then yanked the line into a new file so I could test just the one line. However, my parsing script works OK with the new file - it doesn't throw a UnicodeDecodeError. I don't understand why the one file would generate an error and the other one would not, when they are (on the surface) identical.
Here's what I tried: running enca to determine the file encoding, which complained that it Cannot determine (or understand) your language preferences. file -i says that both files are Regular files. I also deleted every other line in the original log file and still got the error in one file and no error in the other. I tried deleting
set encoding=utf-8
from my .vimrc, writing the file again, and I still got the error in one file and not in the other.
The logs are nginx logs. Nginx has this note in their release notes:
*) Change: now the 0x00-0x1F, '"' and '\' characters are escaped as \xXX
in an access_log.
Thanks to Maxim Dounin.
My Python script has with open('log_file') as f and the error comes up when I try to call json.dumps on a dict.
How can I track this down?
Your question: How can I track this down?
Answer:
(1) Show us the full text of the error message that you got -- without knowing what encoding that you were trying to use, we can't tell you anything. A traceback and a snippet of code that reads the file and reproduces the error would also be handy.
(2) Write a tiny Python script to find the line in the file and then do:
print repr(the_line) # Python 2.X
print ascii(the_line) # Python 3.x
and copy/paste the result into an edit of your question, so that we can see unambiguously what is in the line.
(3) It does look like random gibberish except for the ­ but do tell us whether you expect that line to be text (if so, in what human language?).

Categories