I am using python to develop a basic calculator. My goal is to create an output file of results for a series. I've tried looking for the correct command but haven't had any luck. Below is my current code. I believe all i need it to finish the "def saveSeries(x):" but I am not sure how to. I have created the input file already in the respective folder.
import os
import sys
import math
import numpy
.
.
.
.
def saveSeries(x):
def readSeries():
global x
x = []
input file = open("input.txt", "r")
for line in inputFile:
x.append(float(line))
I believe this question is asking about the saveSeries function. I assume the file structure you want is the following:
1
2
3
4
5
Your solution is very close, but you'll want to iterate over your number list and write a number for each line.
def saveSeries(x):
outfile = open('output.txt', 'w')
for i in x:
outfile.write(str(i) + "\n") # \n will create a new line
outfile.close()
I also noticed your readSeries() was incorrect. Try this instead and call .readlines().
def readSeries():
global x
x = []
inputFile = open("input.txt", "r")
for line in inputFile.readlines():
x.append(float(line))
inputFile.close()
There are lots of ways you could go about accomplishing your goal, so you have to decide how you want to implement it. Do you want to write/update your file every time your user performs a new calculation? Do you want to have a save button, that would save all of the calculations performed?
One simple example:
# Create New File If Doesn't Exist
myFile = open('myCalculations.txt', 'w')
myFile.write("I should insert a function that returns my desired output and format")
myFile.close()
Related
I have a Python script that I want to increment a global variable every time it is run. Is this possible?
Pretty easy to do with an external file, you can create a function to do that for you so you can use multiple files for multiple vars if needed, although in that case you might want to look into some sort of serialization and store everything in the same file. Here's a simple way to do it:
def get_var_value(filename="varstore.dat"):
with open(filename, "a+") as f:
f.seek(0)
val = int(f.read() or 0) + 1
f.seek(0)
f.truncate()
f.write(str(val))
return val
your_counter = get_var_value()
print("This script has been run {} times.".format(your_counter))
# This script has been run 1 times
# This script has been run 2 times
# etc.
It will store in varstore.dat by default, but you can use get_var_value("different_store.dat") for a different counter file.
example:-
import os
if not os.path.exists('log.txt'):
with open('log.txt','w') as f:
f.write('0')
with open('log.txt','r') as f:
st = int(f.read())
st+=1
with open('log.txt','w') as f:
f.write(str(st))
Each time you run your script,the value inside log.txt will increment by one.You can make use of it if you need to.
Yes, you need to store the value into a file and load it back when the program runs again. This is called program state serialization or persistency.
For a code example:
with open("store.txt",'r') as f: #open a file in the same folder
a = f.readlines() #read from file to variable a
#use the data read
b = int(a[0]) #get integer at first position
b = b+1 #increment
with open("store.txt",'w') as f: #open same file
f.write(str(b)) #writing a assuming it has been changed
The a variable will I think be a list when using readlines.
I'm trying to write a simple Phyton script that alway delete the line number 5 in a tex file, and replace with another string always at line 5. I look around but I could't fine a solution, can anyone tell me the correct way to do that? Here what I have so far:
#!/usr/bin/env python3
import od
import sys
import fileimput
f= open('prova.js', 'r')
filedata = f,read()
f.close ()
newdata = "mynewstring"
f = open('prova.js', 'w')
f.write(newdata, 5)
f.close
basically I need to add newdata at line 5.
One possible simple solution to remove/replace 5th line of file. This solution should be fine as long as the file is not too large:
fn = 'prova.js'
newdata = "mynewstring"
with open(fn, 'r') as f:
lines = f.read().split('\n')
#to delete line use "del lines[4]"
#to replace line:
lines[4] = newdata
with open(fn,'w') as f:
f.write('\n'.join(lines))
I will try to point you in the right direction without giving you the answer directly. As you said in your comment you know how to open a file. So after you open a file you might want to split the data by the newlines (hint: .split("\n")). Now you have a list of each line from the file. Now you can use list methods to change the 5th item in the list (hint: change the item at list[4]). Then you can convert the list into a string and put the newlines back (hint: "\n".join(list)). Then write that string to the file which you know how to do. Now, see if you can write the code yourself. Have fun!
This question already has answers here:
Write and read a list from file
(3 answers)
Closed 8 years ago.
I was wondering how I can save a list entered by the user. I was wondering how to save that to a file. When I run the program it says that I have to use a string to write to it. So, is there a way to assign a list to a file, or even better every time the program is run it automatically updates the list on the file? That would be great the file would ideally be a .txt.
stuffToDo = "Stuff To Do.txt"
WRITE = "a"
dayToDaylist = []
show = input("would you like to view the list yes or no")
if show == "yes":
print(dayToDaylist)
add = input("would you like to add anything to the list yes or no")
if add == "yes":
amount=int(input("how much stuff would you like to add"))
for number in range (amount):
stuff=input("what item would you like to add 1 at a time")
dayToDaylist.append(stuff)
remove = input("would you like to remove anything to the list yes or no")
if add == "yes":
amountRemoved=int(input("how much stuff would you like to remove"))
for numberremoved in range (amountRemoved):
stuffremoved=input("what item would you like to add 1 at a time")
dayToDaylist.remove(stuffremoved);
print(dayToDaylist)
file = open(stuffToDo,mode = WRITE)
file.write(dayToDaylist)
file.close()
You can pickle the list:
import pickle
with open(my_file, 'wb') as f:
pickle.dump(dayToDaylist, f)
To load the list from the file:
with open(my_file, 'rb') as f:
dayToDaylist = pickle.load( f)
If you want to check if you have already pickled to file:
import pickle
import os
if os.path.isfile("my_file.txt"): # if file exists we have already pickled a list
with open("my_file.txt", 'rb') as f:
dayToDaylist = pickle.load(f)
else:
dayToDaylist = []
Then at the end of your code pickle the list for the first time or else update:
with open("my_file.txt", 'wb') as f:
pickle.dump(l, f)
If you want to see the contents of the list inside the file:
import ast
import os
if os.path.isfile("my_file.txt"):
with open("my_file.txt", 'r') as f:
dayToDaylist = ast.literal_eval(f.read())
print(dayToDaylist)
with open("my_file.txt", 'w') as f:
f.write(str(l))
for item in list:
file.write(item)
You should check out this post for more info:
Writing a list to a file with Python
Padraic's answer will work, and is a great general solution to the problem of storing the state of a Python object on disk, but in this specific case Pickle is a bit overkill, not to mention the fact that you might want this file to be human-readable.
In that case, you may want to dump it to disk like such (this is from memory, so there may be syntax errors):
with open("list.txt","wt") as file:
for thestring in mylist:
print(thestring, file=file)
This will give you a file with your strings each on a separate line, just like if you printed them to the screen.
The "with" statement just makes sure the file is closed appropriately when you're done with it. The file keyword param to print() just makes the print statement sort of "pretend" that the object you gave it is sys.stdout; this works with a variety of things, such as in this case file handles.
Now, if you want to read it back in, you might do something like this:
with open("list.txt","rt") as file:
#This grabs the entire file as a string
filestr=file.read()
mylist=filestr.split("\n")
That'll give you back your original list. str.split chops up the string it's being called on so that you get a list of sub-strings of the original, splitting it every time it sees the character you pass in as a parameter.
Here's my code:
from random import random
f = open('Attractors1.txt', 'w')
for i in range(10):
theta = (3.14/2)*random()
f.write(str(theta))
I'm trying to create a list of 10 theta values so I can call them in another program, but I don't think the objects are writing correctly. How do I know if I'm doing it write? Whenever I run the code and execute f.read() I get an error saying the file isn't open.
You can't read from a file opened in write-only mode. :)
Since you're not writing within the loop, you'll only actually spit out a single number. Even if you fixed that, you'd get a bunch of numbers all in one line, because you're not adding newlines. .write isn't like print.
Also it's a good idea to use with when working with files, to ensure the file is closed when you think it should be.
So try this:
import math
from random import random
with open('Attractors1.txt', 'w') as f:
for i in range(10):
theta = (math.PI / 2) * random()
f.write("{0}\n".format(theta))
f = open('Attractors1.txt', 'w')
for i in range(10):
theta = (3.14/2)*random()
f.write(str(theta))
f.close()
Then to read:
f = open('Attractors1.txt','r')
text = f.read()
print text
Edit: wups beaten to it
I'm new to programming pretty much in general and I am having difficulty trying to get this command to print it's output to the .txt document. My goal in the end is to be able to change the term "Sequence" out for a variable where I can integrate it into a custom easygui for multiple inputs and returns, but that's a story for later down the road. For the sake of testing and completion of the current project I will be just manually altering the term.
I've been successful in being able to get another program to send it's output to a .txt but this one is being difficult. I don't know if I have been over looking something simple, but I have been grounded for more time than I would like to have been on this.
When the it searches for the lines it prints the fields in the file I want, however when it goes to write it finds the last line of the file and then puts that in the .txt as the output. I know the issue but I haven't been able to wrap my head around how to fix it, mainly due to my lack of knowledge of the language I think.
I am using Sublime Text 2 on Windows
def main():
import os
filelist = list()
filed = open('out.txt', 'w')
searchfile = open("asdf.csv")
for lines in searchfile:
if "Sequence" in lines:
print lines
filelist.append(lines)
TheString = " ".join(filelist)
searchfile.close()
filed.write(TheString)
filed.close()
main()
It sounds like you want to the lines you are printing out collected in the variable "filelist", which will then be printed to the file at the .write() call. Only a difference of indentation (which is significant in Python) prevents this from happening:
def main():
import os
filelist = list()
filed = open('out.txt', 'w')
searchfile = open("asdf.csv")
for lines in searchfile:
if "Sequence" in lines:
print lines
filelist.append(lines)
TheString = " ".join(filelist)
searchfile.close()
filed.write(TheString)
filed.close()
main()
Having
filelist.append(lines)
at the same level of indentation as
print lines
tells Python that they are in the same block, and that the second statement also belongs to the "then" clause of the if statement.
Your problem is that you are not appending inside the loop, as a consequence you are only appending the last line, do like this:
for lines in searchfile:
if "Sequence" in lines:
print lines
filelist.append(lines)
BONUS: This is the "pythonic" way to do what you want:
def main():
with open('asdf.csv', 'r') as src, open('out.txt', 'w') as dest:
dest.writelines(line for line in src if 'sequence' in line)
def main():
seq = "Sequence"
record = file("out.txt", "w")
search = file("in.csv", "r")
output = list()
for line in search:
if seq in line: output.append(line)
search.close()
record.write(" ".join(output))
record.close()