Python keeps closing after I try and run a script. It runs fine and works perfect in my IDE, but when I run the .py from file explorer, it immediately closes, and doesn't write to the file as directed.
I want the program to delete all text on the file, then write 'ToWrite' 4 times.
my_file = open(r"C:\Users\shady\Desktop\copy\python\myfile.txt", "w")
my_file.write("")
my_file.close()
time = [1,1,1,1]
ToWrite = "hello\n"
for x in time:
my_file = open("myfile.txt", "a")
my_file.write(ToWrite)
my_file.close()
I want the program to delete all text on the file, then write 'ToWrite' 4 times.
I tried removing these lines of code from my larger project, and it ran with no isues.
I presume you are running this via the command prompt, and so should be able to see the error message. Please post that also. The main problem is that you are not escaping the backslash.
Try this:
my_file = open("C:\\Users\\shady\\Desktop\\copy\\python\\myfile.txt", "w")
or this:
my_file = open("C:/Users/shady/Desktop/copy/python/myfile.txt", "w")
or this:
import os
filepath = os.sep.join(["C:", "Users", "shady", "Desktop", "copy", "python", "myfile.txt"])
my_file = open(filepath,"w")
If you are not familiar with the command prompt. Open the Windows Start menu and type cmd then select the cmd prompt.
Inside here use cd to change the directory to where your python program is located, then run
py yourprogram.py
Related
I'm trying to create a file with my script and move it just after the creation. The code that creates the file:
fh.seek(0)
with open(file_path, 'wb') as f:
shutil.copyfileobj(fh, f)
f.close()
And the command that moves it just after:
os.system('mv caderneta.db caderneta.db ' + PATH_TO_DB_FOLDER)
The thing is, if the execution ends just after the first part of the code, the file is created, but if the os command is on the code it doesn't create the file and the command shows an error.
I've tried executing it on a shell script file after the execution of the python file but it still doesn't working, showing the same problems.
You have an extra argument to the mv command. It should just be:
os.system('mv caderneta.db ' + PATH_TO_DB_FOLDER)
But you shouldn't use os.system() for this, use shutil.move()
shutil.move('caderneta.db', PATH_TO_DB_FOLDER)
I am working on Debian Stable Linux which is otherwise working very well. I have following code in a python script file named "myrev" which works to reverse order of lines of given text file:
#! /usr/bin/python3
import sys
if len(sys.argv) < 2:
print("Usage: myrev infile")
sys.exit()
try:
with open(sys.argv[1], "r") as f:
lines = f.read().split("\n")
except:
print("Unable to read infile.")
sys.exit()
lines.reverse()
print("\n".join(lines))
It works properly and prints out reverse order of lines if I use following Linux command
./myrev infile
However, if I try to redirect output with following command to original file, a blank file is generated:
./myrev infile > infile
After above command, infile becomes an empty file.
Why can't I redirect output to original file and how can this be solved?
Using > opens the target file for write, same as if opened via fopen with mode "w". That immediately truncates the file, before your program even launches (it happens while the shell is configuring the environment before execing your program). You can't use this approach to read from a file and replace it as a single step. Best you could do would be something like:
./myrev infile > infile.tmp && mv -f infile.tmp infile
where, if the command succeeds, you complete the work by replacing the original file with the contents of the new file.
So, I'm in the windows environment.
I created the text file with notepad.
I saved it in my documents.
I opened python's idle shell.
I used testFile = open("test.txt","a+")
Typed testFile.read()
Hit enter and the result was '' two single quotes?
You need to specify the full path to your text file if it is not in your current working directory:
testFile = open("c:/Users/yourusername/My Documents/text.txt")
testFile = open("test.txt", "rb")
testFile.read()
I converted simple "Hello world ... press enter" script, and converted it to .exe using cx_Freeze module. It runs fine. When i tried to convert littlebit complex script and run it, I got problem. The script it self runs perfect but .exe wouldn't work.
symptom: .exe starts, command line flashes once and nothing happens.
Scripts structure: Uses only os module and sys module.
Scripts funktions: basicly reads and writes a .txt file
script flow:
1. changes cwd
2. opens .txt
3. reads .txt to a list
4. changes the cell in a list where certain string is located
5. writes the list back in the file
6. closes the file
7. waits to user in put to end (sys.stdin.readline())
I cant figure out what is wrong.
import os
import sys
#change cwd
os.chdir('S:/user_name/')
#locate the line where "sertain_string: False" is
file = open('Test_dir/test.txt', 'r+')
lines= file.readlines()
file.close()
x = 0
while(lines[x] != "certain_string: False\n"):
x = x + 1
continue
else:
print("certain_string is on line", + x)
print("\n")
#Read the lines to the list
file = open('Test_dir/test.txt', 'r+')
lines = fiel.readlines()
file.close()
print("\n")
#Change the cell where "certain_string: false" is to "certain_string: True"
lines[x] = 'certain_string: True\n'
print("\n")
#write the list back to the file
file = open('Test_dir/test.txt', 'w+')
file.writelines(lines)
file.close()
print("Done... press enter:")
r = sys.stdin.readline()
I run .exe file from command line.
Error report:
cf_freeze console.py line 26:
Code = importer.get_code(moduleName)
zipimport.ZipImportError: Can't find module 'client_v.0.02__main__'.
I don't understand this. It tries to find client_v.0.02__main__ module from the .zip file, which is module library created during .py to .exe convertion.
My .py file name is "Client_v.0.02".
I figured out. My scripts file name was the issue. During conversion, cx_freeze made module library .zip, but the location of the scripts main module was affected by the name. A dot in the name made a subdirectory to library .zip file so the path to main was wrong and couldn't be found.
I am running 32-bit Windows 7 and Python 2.7.
I am trying to write a command line Python script that can run from CMD. I am trying to assign a value to sys.argv[1]. The aim of my script is to calculate the MD5 hash value of a file. This file will be inputted when the script is invoked in the command line and so, sys.argv[1] should represent the file to be hashed.
Here's my code below:
import sys
import hashlib
filename = sys.argv[1]
def md5Checksum(filePath):
fh = open(filePath, 'rb')
m = hashlib.md5()
while True:
data = fh.read(8192)
if not data:
break
m.update(data)
return m.hexdigest()
# print len(sys.argv)
print 'The MD5 checksum of text.txt is', md5Checksum(filename)
Whenver I run this script, I receive an error:
filename = sys.argv[1]
IndexError: list index out of range
To call my script, I have been writing "script.py test.txt" for example. Both the script and the source file are in the same directory. I have tested len(sys.argv) and it only comes back as containing one value, that being the python script name.
Any suggestions? I can only assume it is how I am invoking the code through CMD
You should check that in your registry the way you have associated the files is correct, for example:
[HKEY_CLASSES_ROOT\Applications\python.exe\shell\open\command]
#="\"C:\\Python27\\python.exe\" \"%1\" %*"
The problem is in the registry. Calling python script.py test.txt works, but this is not the solution. Specially if you decide to add the script to your PATH and want to use it inside other directories as well.
Open RegEdit and navigate to HKEY_CLASSES_ROOT\Applications\python.exe\shell\open\command. Right click on name (Default) and Modify. Enter:
"C:\Python27\python.exe" "%1" %*
Click OK, restart your CMD and try again.
try to run the script using python script.py test.txt, you might have a broken association of the interpreter with the .py extention.
Did you try sys.argv[0]? If len(sys.argv) = 0 then sys.argv[1] would try to access the second and nonexistent item