Can't append a PyCharm file - python

I'm a newbie programmer , I'm coding this account tool for a game (Just for myself, can only run it in the console for now)
To do this I needed a database but what I did was creating a Python file with my class, and another one that is interactive and it has to append some things you type to the other Python file , the one with the class, so it automatically saves on both files.
At first I did this
action = input('Select an action')
if action == 'addw':
champion = input('\n'+'Select a champion \n')
f = open('/Users/tommaso/PycharmProjects/Random/Champs.py', 'a')
f.write('\n' + str(champion.title()) + r'.addw()')
print('\nA Win was added to' + ' '+ str(champion))
And it works. However, I at the end of my program (not just the code up there) it would just stop, and since I needed it to restart or at least give me the option to restart/quit, I had to use a while loop, so at first I tried if it worked with a while loop, and I did this (just a scratch):
while True:
try:
x = open('/Users/tommaso/PycharmProjects/Random/Champs.py', 'a')
x.write('hello')
except: break
And this , too, worked.
So I made a big while loop with everything from my first console file, using the exact same method to append the action, but it doesn't work.
Doesn't give me any error, but it doesn't append anything, here's the code:
while True:
try:
action = input('Welcome to your own account tool.\n' + 'Select an action:\n' + 'addw,addl\n' + 'getstats,getallstats,lanes\n\n')
if action == 'addw':
champion = input('\n' + 'Select a champion \n')
f = open('/Users/Tommaso/PycharmProjects/Random/Champs.py', 'a')
f.write('\n' + str(champion.title()) + r'.addw()')
print('\nA Win was added to' + ' ' + str(champion))
except: Exceptaction = input('Exit / Restart')
if Exceptaction== 'Exit':
break
else:
pass
But it doesn't work, it just doesn't append what I tell him to my file.
Anyone knows why and how can I fix this?
Thanks in advance!!

I would recommend writing to a text file rather than writing to the actual python file.
A python file (Python Program /Python Script) is used to carry out the tasks you desire (the actual program).
Where as a text file is commonly used to store and read the data for the python program.
Working with .txt or text files in python is really easy.
You could also use mySQL to create a Data Base to store and retrieve data but I would suggest starting with the text files for now and once you understand that method progress to mySQL, that way you will learn two common methods of storing and fetching data.
PS: Working with text files is quick and simple it will save a headache. Also look up some free PDF books via a google advanced search, you will have so much tutorials, you will not know where to start !!.
Hope this helps. Happy Coding :).

Related

Is It Possible to Make a File with a Function in Python?

I am trying to make a file with a function in python, but I have no idea how. This is what I have, and what I need.
def file_maker():
file_number = input("What number player are you? ")
#Insert however you make a file in code, naming it ('inventory.' + filenumber + '.txt')
I only need to know how I would initiate the file-making process. I tried googling it, but the only thing that comes up is how to access a function within a different file. I am an amateur programmer, any and all suggestions are welcome. Thanks for your time.
def file_maker():
file_number = input("What number player are you? ")
with open("inventory.%s.txt" % file_number, "w") as f:
# Do whatever you need with the file using the 'f' to refer to the file object
pass # in case you don't want to do anything with the file, but just create it
Read more regarding open function here: Open function
FYI, this will overwrite the file if it already exists.
To create a file, just open in it write mode.
file_handle=open ('inventory.' + filenumber + '.txt', "w")
file_handle is now an object that you can use various methods on to add content to the file. Read the documentation here.
Make sure you close the file when you are done with it using file_handle.close()
Note: Although this method works, it is usually considered better practice to use with, as shown in the other answer. It uses less code and automatically closes the file when done.

Reading a file, only if no other 'process' is working on it

I want to open 3 Powershell and run the same code at the 3 of them, just different files.
As they'll have exactly the same logic, each of them will try to access each other's files to check if there's anything written there
Process1 has client1.txt, Process2 has client2.txt and Process3 has client3.txt
Here's some code as to what process 3 should check before choosing which problem to work on:
import os
while True:
f = 'C:\Users\Files'
i = {}
i['word'] = 'problem X' #just an example, I'll have a whole list
if os.path.exists(f):
try:
os.rename(f, f)
print 'Access on file "' + f +'" is available!'
file1 = open('C:\Users\Files\client1.txt', 'r+')
file2 = open('C:\Users\Files\client2.txt', 'r+')
if file1.read() == i['word']:
print "A process is already working on this problem, check another"
elif file2.read() == i['word']:
print "A process is already working on this problem, check another"
else:
print "Found a new problem to work on"
file3 = open('C:\Users\Files\client3.txt', 'r+')
file3.write(i['word'])
file1.close()
file2.close()
file3.close()
except OSError as e:
print 'Access-error on file "' + f + '"! \n' + str(e)
time.sleep(5)
pass
What I tried to represent through the code is: I only want a process to start a problem if the others aren't working on it already, as they all have the same logic they'll try to solve the same problem (I have lots that need solving) and so they might reach at around the same time as the program goes on with the while True.
When it finishes the problem, it'll delete the contents of the file and pick a new problem, then write the problem it is working at in its own file for the others to check later.
Just to make it a bit clear: Let's say process1 found a problem to work first ('AAA'), they all have empty txt files, it'll check txt2 and txt3 and see it's not equal to ('AAA'), then it'll write it to its own file and close it.
I want process2 which might make it there a second later to read both txt1 and txt3 and see that ('AAA') is already being worked on, it'll get the next in the list and check again, seeing that ('BBB') is okay and it'll write on its own file.
When it ends, it deletes the String from the txt and starts looking for another one.
There's the problem of both process trying to check files at the same time too. Maybe if there's a way to put a time.sleep() to a process if another process is using the file and then try again a bit later?
Ideally you would use Python's multiprocessing module to start each process. You could have one process watch for new files and feed them to a queue that your worker processes read from. This solution would eliminate the need for any file locking since only one process is ever looking for new files.
If you must start the processes via Power Shell though, you'll have to use locking of some sort to get the processes working together. True file locking is difficult to do in a cross platform way. You can fake it by using move though. For instance, you could attempt to move the file (move is atomic on most operating system assuming you're moving to a location on the same filesystem). If the move fails, you know another process must have gotten to it first, or something went terribly wrong with the OS. You can then do all your processing on the moved file. For example:
import path
import shutil
filename = "C:\\path\\to\\filename.txt"
_filename = os.path.join(os.path.basename(filename), ".wip")
wip_filename = os.path.join(os.path.dirname(filename), _filename)
try:
shutil.move(filename, wip_filename)
except OSError:
# another process moved it first
pass
else:
do_work(wip_filename)

Running python script on web browser

I am new to python. I have created a Script which asks the user to add date and file name and then generates csv file. I want to run that Script on our network. So that everyone on the network can put the dates and generate their report. Can anybody please suggest me which module should i use and how.Although my script is generating two files , i only want everyone to download Revenue report not the missing id's.
here is the snippet from my program which is calling all of my functions,i made.
Thanks in advance.
print "Enter state date(eg:-2015-01-01):",
start_date = raw_input()
print "Enter the last date(eg:-2015-01-01):",
end_date=raw_input()
print "Please give a filename for this report(eg:-January_rev_report): ",
file_name=raw_input()
in_file = open(""+file_name+".csv", "w")
in_file2=open("missiong_ids.csv","w")
in_file2.write("Missing_ids\n")
in_file.write("Partner_id|Partner_name|Price_of_lead|Date|Osdial_Lead_id|Bob_lead_id|list_id|Phone_number|State|Postal_code|Status\n")
data_=getPidsForThisMonth(start_date,end_date)
for j in data_:
if getReport(j,start_date,end_date) is None:
missing_ids=""
missing_ids+=j
#print missing_ids + " is missing id, the whole list of missing id's will be added to missing_ids.csv file "
in_file2.write(missing_ids)
else:
data=""
details = getPartnerDetails(j)
pid = str(details[0])
name = str(details[1])
price = str(details[2])
report_data=getReport(j,start_date,end_date)
date=str(report_data[0])
lead_id=str(report_data[1])
bob_id=str(report_data[2])
list_id=str(report_data[3])
phone=str(report_data[4])
state=str(report_data[5])
postal_code=str(report_data[6])
status=str(report_data[7])
data+=pid+"|"+name+"|"+price+"|"+date +"|"+lead_id+"|"+bob_id+"|"+list_id+"|"+phone+"|"+state+"|"+postal_code+"|"+status
data+="\n"
in_file.write(data)
Flask would be suited to turn this into a small web-app: http://flask.pocoo.org/
I would have one controller that takes two parameters, the start- and end-date. Or better have a small page where dates can be selected and pass this using POST to a controller. This would run the script and return the file. If you set the response correctly the csv file will start as a download.
You won't need to write the file, just store the lines in a list and at the end generate the full content using '\n'.join(lines).

Save Outfile with Python Loop in SPSS

Ok so I've been playing with python and spss to achieve almost what I want. I am able to open the file and make the changes, however I am having trouble saving the files (and those changes). What I have (using only one school in the schoollist):
begin program.
import spss, spssaux
import os
schoollist = ['brow']
for x in schoollist:
school = 'brow'
school2 = school + '06.sav'
filename = os.path.join("Y:\...\Data", school2) #In this instance, Y:\...\Data\brow06.sav
spssaux.OpenDataFile(filename)
#--This block are the changes and not particularly relevant to the question--#
cur=spss.Cursor(accessType='w')
cur.SetVarNameAndType(['name'],[8])
cur.CommitDictionary()
for i in range(cur.GetCaseCount()):
cur.fetchone()
cur.SetValueChar('name', school)
cur.CommitCase()
cur.close()
#-- What am I doing wrong here? --#
spss.Submit("save outfile = filename".)
end program.
Any suggestions on how to get the save outfile to work with the loop? Thanks. Cheers
In your save call, you are not resolving filename to its actual value. It should be something like this:
spss.Submit("""save outfile="%s".""" % filename)
I'm unfamiliar with spssaux.OpenDataFile and can't find any documentation on it (besides references to working with SPSS data files in unicode mode). But what I am going to guess is the problem is that it grabs the SPSS data file for use in the Python program block, but it isn't actually opened to further submit commands.
Here I make a test case that instead of using spssaux.OpenDataFile to grab the file, does it all with SPSS commands and just inserts the necessary parts via python. So first lets create some fake data to work with.
*Prepping the example data files.
FILE HANDLE save /NAME = 'C:\Users\andrew.wheeler\Desktop\TestPython'.
DATA LIST FREE / A .
BEGIN DATA
1
2
3
END DATA.
SAVE OUTFILE = "save\Test1.sav".
SAVE OUTFILE = "save\Test2.sav".
SAVE OUTFILE = "save\Test3.sav".
DATASET CLOSE ALL.
Now here is a paired down version of what your code is doing. I have the LIST ALL. command inserted in so you can check the output that it is adding the variable of interest to the file.
*Sequential opening the data files and appending data name.
BEGIN PROGRAM.
import spss
import os
schoollist = ['1','2','3']
for x in schoollist:
school2 = 'Test' + x + '.sav'
filename = os.path.join("C:\\Users\\andrew.wheeler\\Desktop\\TestPython", school2)
#opens the SPSS file and makes a new variable for the school name
spss.Submit("""
GET FILE = "%s".
STRING Name (A20).
COMPUTE Name = "%s".
LIST ALL.
SAVE OUTFILE = "%s".
""" %(filename, x,filename))
END PROGRAM.

Python - read and write input from user

I am having trouble writing this short program for my python class I was hoping someone could offer some assistance.
What I would like to accomplish:
1. Write a program that uses a while loop to accept input from the user (if the user presses Enter, exit the program).
2. Save the input to a file, then print it.
3. Upon starting, the program will display the current contents of the file.
Example:
Start program for first time.
Enter text: this is input
this is input.
Enter text: some more text
this is input. some more text.
When you start the program for a second time
this is input. some more text.
Enter text:
etc. etc.
What I have so far:
intext = open('user_input.txt','a')
intext.close()
string_input = input('Enter text: ')
while True:
open_input = open('user_input.txt','r')
if open_input:
for i in open_input:
print(i)
if string_input != "":
uinput = open('user_input.txt','a')
uinput.write(string_input + '.')
uinput.close()
rd = open('user_input.txt', 'r')
if rd:
for line in rd:
print(line)
if string_input == "":
t = open('user_input.txt', 'r')
for line in t:
print(line)
t.close()
break
Problems: Upon opening, any previously stored text does not display. If a user inputs text it prints in an infinite loop, and does not prompt to enter text again.
Positives: The input is recorded to the text file. If no text is entered, when exiting any previously entered text does display correctly.
Like I said, this is homework for me. I have searched for the answer, but I seem to be ripping the code apart and putting it back together only to get different errors. So some guidance on this would be greatly appreciated.
One thing I forgot to mention is that I am using Python 3.
Thanks again to David for helping me think more like a programmer. Here are the results:
intext = open('user_input.txt','r').readline()
print(intext)
while True:
string_input = input('Enter text: ')
if string_input == "":
t = open('user_input.txt', 'r').readline()
print(t)
break
if string_input != "":
d = open('user_input.txt', 'a')
d.write(string_input + '. ')
d.close()
n = open('user_input.txt', 'r').readline()
print(n)
I tried to keep the code as slim as possible, and it works now.
A couple questions additional questions that came out of this:
Do I need to close the file at the end? When I tried to close apnd and n , It gave me errors.
While looking for answers I came a across, this. Is it still best practice to use a "with" statement?
Example:
with open("x.txt") as f:
data = f.read()
do something with data
To be honest, your program as you've shown it is kind of a mess. I say this not to be insulting, but because you do have a pretty clear list of the steps your program needs to take, and I think you will wind up with a better understanding by scrapping your existing code and starting from scratch.
In your question, you listed the following steps:
Upon starting, display any previous content of the file
Use a while loop to
Accept input from the user
If the user presses Enter, exit the program
Save the input to a file
Print it (note: did you mean to print just the latest input, or everything in the file?)
Turning your overall task into a list of specific steps like this is probably 80% of the work of writing a computer program. All that's left to do is translate it into code. So I would suggest that you consider how to do each of these steps individually.
Write a code snippet to display the contents of a file
Write a code snippet to read a line of input from the user and store it in a variable
Write a code snippet to check the contents of a variable to see whether it's empty, and if so, exit
Write a code snippet to append the contents of a variable to a file
Write a code snippet to print the contents of a variable (or of a file, if that's what you meant to do)
Each of these can be done in one or two lines, so individually, you should have an easy time with them. Once you've done all the pieces, all you need to do is put them together:
# display the contents of the file
while True:
# read a line of input and store it in a variable
# check the contents of the variable to see if it's empty, and if so, exit
# append the contents of the variable to the file
# print the contents of the variable (or of the file)
Update: This is not a big deal, but you have an unnecessary if statement (the second one) in your revised program. Think about this: if string_input is empty, Python will execute the break statement, which terminates the loop immediately. So you'll only ever reach the second if statement if string_input is not empty. That means the condition string_input != "" is guaranteed to be true at that point in the program, and there's no need to check it.
Do I need to close the file at the end? When I tried to close apnd and n , It gave me errors.
Yes you do. Look at the pattern you used with d:
# open the file
d = open('user_input.txt', 'a')
# write to it (or read from it)
d.write(string_input + '. ')
# close it
d.close()
You should do the same thing every time you open a file, namely with intext, t, and n: open it, read from it, and then immediately close it.*
I'm guessing that the reason you encountered errors is that you tried to put the .close() statements at the end of the program, outside of the if statement and perhaps even outside of the while loop. That would give you a NameError because the variables n and t are not defined at those points in the program. They "expire" at the end of the block they are defined in. For more information on this, read up on scoping. (The Wikipedia article is probably not the best introduction, but you can search Stack Overflow and/or the web for more resources.)
While looking for answers I came a across, this. Is it still best practice to use a "with" statement?
Yes, the with statement is relatively new to Python and is the recommended way to do "quick" file I/O operations like this. Basically the with block takes care of closing the file at the end. For example, the code snippet above involving d is equivalent to
# open the file
with open('user_input.txt', 'a') as d:
# write to it (or read from it)
d.write(string_input + '. ')
# Python "automatically" closes it for you
*This "open-read/write-close" pattern of file access is usually a good idea. I've told you to use it in your program because it's important for you to learn how to split a program into small steps and convert each of the steps into code individually. But when you are writing a program that repeatedly writes things out to a file, or reads them in from a file, sometimes it is actually better to just open the file once in the beginning and just keep it open, rather than opening and closing it every time. If you are curious, one thing you could investigate is how to modify your program to reduce the number of times it has to open and close the file.
Use raw_input instead of input.
You forget to call input in the while loop
BTW, why not write data just at exit of the program instead of in each loop?

Categories