I am trying to get my program to write over a simple config.txt file.
Which is actually working: it writes the new content over the old one if one condition is met and proceeds to the next block.
However, when the next block calls another function of my program, the content of the file simply dissapears: the .txt file becomes empty.
I have searched SO for similar issues but couldn't find any posts.
I looked into:
How to search and replace text in a file using Python?
Search and replace a line in a file in Python
And and got some of these to work but always ran into the issue above.
Please be gentle as I am a newbie and this is my first "not Hello_world" program and my first post. Thanks:)
>>>Content of the default config.txt file is 'runcount=0'
def alias(confirmation):
###First block###
if confirmation.lower()=='yes':
print("...")
config=open('config.txt','r')
data=config.read()
config.close()
newdata=data.replace('runcount=0','runcount=1')
config=open('config.txt','w')
config.write(newdata)
config.close()
confirmation2=input()
>>>Content of the config.txt file is now 'runcount=1'
###Second block###
if confirmation2.lower()=='yes':
print("...")
return main()
else:
...
>>>The main() function is called... However the config.txt file is now empty
I choose to show you this code because I think it is the most readable.
I tried the "with" method which gives me the same results.
I also tried to write to a new file, remove the default and rename the new to config.txt... same issue.
I don't get why the file becomes empty as I closed it.
No error msg, my program just goes on but the file is empty.
Please note that I used open(config.txt, 'r') in another function of my program, only once yet.
It happens that I coded the following line in main() and did not close config.txt:
config=open("config.txt","w+")
And forgot about it...
Thank you guys for the hint.
I'm going to hide somewhere very dark now.
Related
I'm trying to Create a file and append all the content being calculated into that file, but when I run the script the very last iteration is written inside the file and nothing else.
My code is on pastebin, it's too long, and I feel like you would have to see exactly how the iteration is happening.
Try to summarize it, Go through an array of model numbers, if the model number matches call the function that calculates that MAC_ADDRESS, when done calculating store all the content inside a the file.
I have tried two possible routes and both have failed, giving the same result. There is no error in the code (it runs) but it just doesn't store the content into the file properly there should be 97 different APs and it's storing only 1.
The difference between the first and second attempt,
1 attempt) I open/create file in the beginning of the script and close at the very end.
2 attempt) I open/create file and close per-iteration.
First Attempt:
https://pastebin.com/jCpLGMCK
#Beginning of code
File = open("All_Possibilities.txt", "a+")
#End of code
File.close()
Second Attempt:
https://pastebin.com/cVrXQaAT
#Per function
File = open("All_Possibilities.txt", "a+")
#per function
File.close()
If I'm not suppose to reference other websites, please let me know and I'll just paste the code in his post.
Rather than close(), please use with:
with open('All_Possibilities.txt', 'a') as file_out:
file_out.write('some text\n')
The documentation explains that you don't need + to append writes to a file.
You may want to add some debugging console print() statements, or use a debugger like pdb, to verify that the write() statement actually ran, and that the variable you were writing actually contained the text you thought it did.
You have several loops that could be a one-liner using readlines().
Please do this:
$ pip install flake8
$ flake8 *.py
That is, please run the flake8 lint utility against your source code,
and follow the advice that it offers you.
In particular, it would be much better to name your identifier file than to name it File.
The initial capital letter means something to humans reading your code -- it is
used when naming classes, rather than local variables. Good luck!
When I run the following code:
f = new File(projectroot + "/outputTest1.csv")
f.append("hello world" + '\n')
Here is the result in csv file:
hello world
hello world
Why is it displaying a duplicate?
Take note: I'm using groovy in soapUI
Append adds given string to the end of the file, so when you run it for the third time, it should display 3 hello worlds.
Two possible explanations there :
You're not clearing the file content before writing to it, which means you'll add a new line with "Hello world" every time you execute your code. Either :
use the "Write" method instead of "Append"
clear the file using file.bytes = new byte[0]
You call this piece of code twice, which can be checked by adding a log/display and checking if your log only appears once.
Further reading :
SO question about file clearing
Groovy documentation about file handling
I was using this code inside of an assertion of SoapUI then created duplicate. When I added a separate groovy step with the same code then it worked correctly.
I am creating something along the likes of a text adventure game. I have a .yaml file that is my input. This file looks something like this
node_type:
action
title:
Do some stuff
info:
This does some stuff and things
script:
'print("hello world")
print(ret_val)
foo.bar(True)
ret_val = (foo.bar() == True)
if (thing):
print(thing)
print(ret_val)
'
My end goal is to have my python program run the script portion of the yaml file exactly as if it had been copy pasted into the main code. (I know there are about ten bazillion security reasons I should not be running user input like this, but I am the only one writing these nodes, and the only one using this program so I'm mostly just ignoring this fact...)
Currently my attempt goes like this: I load my yaml file as a dict using pyyaml
node = yaml.safe_load(file.yaml)
Then I'm trying to use exec to run my code and hitting a lot of problems, I can't run if statements, I simply get a syntax error, and I can't get any sort of return value from my code. I've tried this as a work around:
def main()
ret_val = "test";
thing = exec(node['script'], globals(),locals())
print(ret_val)
which when run with the above .yaml file prints
>> hello world
>> test
>> True
>> test
for some reason not actually modifying any of my main variables even though I fed them to exec.
Is there any way for me to work around these issues or is there an all together better way to be doing this?
One way of doing this would be to parse the code out and save it to a .py file, from which it can be imported dynamically, for example by importlib.
You might want to encapsulate parsed code into a function, which you can then easily call to invoke your action. Also, it would make sense to specify some default imports there.
I'm using the plugin line-by-line to read a very large file. There's a case where I want just the first line, so I'd close the connection immediately in that case.
However, I was noticing that it would try to process the next line regardless. I dumbed it down as far as I could, and wrote this:
lr.on("line", function (line) {
lr.pause();
console.log("\rLine");
lr.close();
}
My console shows:
Line
Line
Without the lr.close(), it only logs Line once.
What am I missing?
Take a look to Source
It print last lineFragment for you.
If you don't need it - call lr.end();.
I have R code as below. Below code resides in a file called 'iot.R'. I am executing it in Linux.
I want to print content of variable 'fileinformation' to a file mentioned by file=fileConn...
I thought that the 3rd line will solve the issue, but it is not giving the required output :(
fileinformation = system(paste("file", filenames[1]))
#print(fileinformation)
cat(print(fileinformation),"\r\n","\r\n", file=fileConn)
When I run the file, i get below result. It prints to my screen, rather than writing to the file :(
> source('iot.R')
CH7Data_20130401T135010.csv: ASCII text, with CRLF line terminators
[1] 0
--------------------update1
I also tried below command, but didnt get the expected rsult
cat(capture.output(fileinformation),"\r\n","\r\n", file=fileConn)
You need to set the intern argument to TRUE in your call to system. For instance:
fileinformation<-system("file cinzia_2.gif",intern=TRUE)
fileinformation
#[1] "cinzia_2.gif: GIF image data, version 89a, 640 x 640"
Of course I tried a file on my pc. Setting intern to TRUE the return value of system becomes the console output of the command. Then, when you call cat, you don't need to enclose fileinformation into print, but a simple cat(fileinformation,"\r\n","\r\n", file=fileConn) will suffice.
Hi Just a comment as I dont have enough rep to comment in the normal way. but cant you use
write.table
to save the output to a file? It may be easier?