I'm super new to Python so I'm wondering if someone can help me out or link me to an appropriate post that explains this?
What I would like to do is
9999**9999
in Python Terminal, then copy the output directly to my clipboard or sent to a file.
I tried in Batch using
py 9999**9999 >>pythonoutput.txt
but only got an error of
python.exe: can't open file '9999**9999': [Errno 22] Invalid argument
and not sure how I could make that work either.
Any ideas? Cheers
Here's how to write (append) to a file:-
obj=open("yourfile.txt","a+") #open a reference to your file, in append mode. (Use 'w' for write, and 'r' for read if you ever need to)
obj.write("your chars, numbers or whatever here") #use this as many times as you want before closing
obj.close() #close your reference once you're done
Try using:
python -c print(9999*9999) > outfile.txt
You might want to use py instead of python there since you seem to have your executable renamed.
Sent to result to file is much easier than to clipboard.
In the python terminal,you can do this:
with open("/home/my/output","w") as file:#start a file object for writing
file.write(str(9999*9999))#write the content
Related
There is no problem accessing the file but while reading I get the following error
from nltk.corpus.reader import WordListCorpusReader
reader= WordListCorpusReader("C:\\Users\samet\\nltk_data\\corpora\\bilgi\samet",
["politika.xls"])
a = reader.words()
print (a)
enter image description here
You'll want to make sure the file you're trying to load (politika.xls) is saved with utf-8 encoding. First I'll detail how I replicated your error, then I'll show an approach to solve it.
I was able to replicate your error as follows:
Create a new text document. "temp.txt"
Open it, add a few lines random text, save and close it.
Rename "temp.txt" to "temp.xls"
Open "temp.xls"
Save as.... "temp.xlsx"
Close file.
Rename "temp.xlsm" to "politika.xls"
Try running your code (with correction to path).
Receive your error: "UnicodeDecodeError: 'utf-8' codec can't decode bytes in position 15-16: invalid continuation byte"
There may be a more straightforward approach, but from the above error condition, this worked to fix it:
Create a backup copy of "politika.xls"
Rename "politika.xls" to "old_politika.xls"
Create a new text file "politika.txt".
#Steps 3.1 - 3.4 may or may not be needed.
3.1. Open "politika.txt"
3.2. Save as...
3.3. Select Encoding >> (either ANSI or UTF-8 should work)
3.4. Save and close file.
Rename "politika.txt" to "politika.csv"
Open up "old_politika.xls"
Select and copy the data.
Open up "politika.csv"
Paste the data. Save and exit.
Rename "politika.csv" to "politika.xls"
Run your program. (See below for code / potential correction)
Also, you'll want to fix your dirrectory path. Make sure you use the excape character "\" for each "\" in the path. You were missing a "\" in front of " \samet" in 2 places. Corrected code below:
from nltk.corpus.reader import WordListCorpusReader
reader= WordListCorpusReader("C:\\Users\\samet\\nltk_data\\corpora\\bilgi\\samet",
["politika.xls"])
a = reader.words()
print (a)
I hope this helps.
i wanted to make a python file that makes a copy of itself, then executes it and closes itself, then the copy makes another copy of itself and so on...
i am not asking for people to write my code and this could be taken as just a fun challenge, but i want to learn more about this stuff and help is appreciated.
i have already played around with it but can't wrap my mind around it,
I've already tried making a py file and just pasting a copy of the file itself in it two different ways i could think of but it would just go on forever.
#i use this piece of code to easily execute the py file using os
os.startfile("file.py")
#and to make new py file i just use open()
file = open("file.py","w")
file.write("""hello world
you can use 3 quote marks to write over multiple lines""")
i expect that when you run the program it makes a copy of itself, runs it, and closes itself, and the newly ran program loops over.
what actually happenes is that either I'm writing code forever or,
when i embed the code it pastes in the copy of itself into what it copies to the copy file,
it rightfully says it doesn't know what that code is because it's being written.
it's all really confusing and this is difficult to explain and I'm sorry
it's midnight atm and I'm tired.
I don't have enough rep to reply to #Prune:
os.startfile(file) only works on Windows, and is replaced by subprocess.call
shutil.copy2(src, dst) works on both Windows and Linux.
Try this solution as well:
import shutil
import subprocess
old_file = __file__
new_file = generate_unique_file_name()
shutil.copy2(old_file, new_file) # works for both Windows and Linux
subprocess.call('python {}'.format(new_file), shell=True)
You're close; you have things in the wrong order. Create the new file, then execute it.
import os
old_file = __file__
new_file = generate_unique_file_name()
os.system('cp ' + old_file + ' ' + new_file) #UNIX syntax; for Windows, use "copy"
os.startfile(new_file)
You'll have to choose & code your preferred method for creating a unique file name. You might want to use a time-stamp as part of the name.
You might also want to delete this file before you exit; otherwise, you'll eventually fill your disk with these files.
I am trying to create a file that just writes the user's name to a file. I have written:
def main():
f=open("name.txt","a")
name=input("name:")
f.writelines(name)
f.close()
main()
I am wondering what I am missing in order for this to work because it does not save into a text file. Additionally I am using append so I can run this program more than once and continuously add names to it.
The code works fine, but I suspect why it doesn't for you.
In the console, using input function, you need to tell the program that you're sending him a string.
When it asks for the name, you shouldn't input for instance Bernard, but "Bernard".
You should use raw_input instead if you want to get rid of the " character.
PS : Have you tried running your program in the console using python command ? You would have seen the error message pop.
input is used to read integers.
Use raw_input instead. A lot of people don't recommend using input.
It is possible a duplicate: link
I'm using Python 2.7 on Windows XP.
My script relies on tempfile.mkstemp and tempfile.mkdtemp to create a lot of files and directories with the following pattern:
_,_tmp = mkstemp(prefix=section,dir=indir,text=True)
<do something with file>
os.close(_)
Running the script always incurs the following error (although the exact line number changes, etc.). The actual file that the script is attempting to open varies.
OSError: [Errno 24] Too many open files: 'path\\to\\most\\recent\\attempt\\to\\open\\file'
Any thoughts on how I might debug this? Also, let me know if you would like additional information. Thanks!
EDIT:
Here's an example of use:
out = os.fdopen(_,'w')
out.write("Something")
out.close()
with open(_) as p:
p.read()
You probably don't have the same value stored in _ at the time you call os.close(_) as at the time you created the temp file. Try assigning to a named variable instead of _.
If would help you and us if you could provide a very small code snippet that demonstrates the error.
why not use tempfile.NamedTemporaryFile with delete=False? This allows you to work with python file objects which is one bonus. Also, it can be used as a context manager (which should take care of all the details making sure the file is properly closed):
with tempfile.NamedTemporaryFile('w',prefix=section,dir=indir,delete=False) as f:
pass #Do something with the file here.
I have written a few lines of code in Python to see if I can make it read a text file, make a list out of it where the lines are lists themselves, and then turn everything back into a string and write it as output on a different file. This may sound silly, but the idea is to shuffle the items once they are listed, and I need to make sure I can do the reading and writing correctly first. This is the code:
import csv,StringIO
datalist = open('tmp/lista.txt', 'r')
leyendo = datalist.read()
separando = csv.reader(StringIO.StringIO(leyendo), delimiter = '\t')
macrolist = list(separando)
almosthere = ('\t'.join(i) for i in macrolist)
justonemore = list(almosthere)
arewedoneyet = '\n'.join(justonemore)
with open('tmp/randolista.txt', 'w') as newdoc:
newdoc.write(arewedoneyet)
newdoc.close()
datalist.close()
This seems to work just fine when I run it line by line on the interpreter, but when I save it as a separate Python script and run it (myscript.py) nothing happens. The output file is not even created. After having a look at similar issues raised here, I have introduced the 'with' parameter (before I opened the output file through output = open()), I have tried flushing as well as closing the file... Nothing seems to work. The standalone script does not seem to do much, but the code can't be too wrong if it works on the interpreter, right?
Thanks in advance!
P.S.: I'm new to Python and fairly new to programming, so I apologise if this is due to a shallow understanding of a basic issue.
Where are the input file and where do you want to save the output file. For this kind of scripts i think that it's better use absolute paths
Use:
open('/tmp/lista.txt', 'r')
instead of:
open('tmp/lista.txt', 'r')
I think that the error can be related to this
It may have something to do with where you start your interpreter.
Try use a absolute path /tmp/randolista.txt instead of relative path tmp/randolista.txt to isolate the problem.