Can't acess file I've just created on script - python

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)

Related

Python closes after running program with writing to file

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

Python subprocess module: what the code does?

What this piece of code is doing?
with open(temp_path) as f:
command = "xdg-open"
subprocess.Popen(
["im=$(cat);" + command + " $im; rm -f $im"], shell=True, stdin=f
)
I'm confused with the subprocess part...
What the shell script does?
im=$(cat)
uses cat to read the standard input, and assigns the result to the variable im. Since you use stdin=f, that reads the contents of temp_path.
command + " $im;`
executes the command xdg-open with $im as its argument. So this uses the contents of the file as the argument to xdg-open, which opens the file in its default application. Since the argument should be a filename, this implies that temp_path contains a filename.
rm -f $im
deletes the file that was opened.
This seems like a silly way to do this. A better way to write it would be:
with open(temp_path) as f:
filename = f.read().strip()
command = "xdg-open"
subprocess.Popen([command, filename])
os.remove(filename)
Although I haven't seen the rest of the script, I suspect the temp path is also unnecessary when doing it this way -- it seems like it was just using that as a way to get the filename into the shell variable.

Cannot redirect python script output to infile

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.

mac os: How do I run a multi-line script on command line?

I have a python file that isn't working.
I would like to run this script on it:
with open('beak', 'rb+') as f:
content = f.read()
f.seek(0)
f.write(content.replace(b'\r', b''))
f.truncate()
Source
I don't know how to make multiple lines on command line and I am not really sure how to execute my code. Do I just put my file name in place of 'beak' and do I just cd to the folder my file is in before I execute this script?
You can type that into the Python command line. Type the first line and return, it will recognize that you're in the middle of a with clause and allow you to type the remaining lines one at a time (be sure to get the indentation right). After the last line, return twice and it will execute.
This script assumes that you are going to read a file named "beak". You need to run this script from the same directory where "beak" is. ("beak" should really have an extension, like ".txt", depending on what kind of file it is).
Doing long scripts from the command line like this is not the best way -- it's better to put this code in a file ("reader.py", for example -- and put reader.py in the same directory as "beak"). Then you can simply execute by typing "python reader.py".

Python script not writing to txt file

I have a Python script that runs properly on my laptop, but when running on my raspberry pi, the following code does not seem to be working properly. Specifically, "TextFile.txt" is not being updated and/or saved.
openfile = open('/PATH/TextFile.txt','w')
for line in lines:
if line.startswith(start):
openfile.write(keep+'\n')
print ("test 1")
else:
openfile.write(line)
print ("test 2")
openfile.close()
I am seeing "test 1" and "test 2" in my output, so I know that the code is being reached, paths are correct, etc
It may be due to a permissions problem. I am running the script from the terminal by using:
usr/bin/python PATH/script.py
Python is owned by "root" and script.py is owned by "Michael".
My first guess:
Does the file exist? If it does not exist then you cannot write to it. Try this to create the file if it does not exist: file = open('myfile.dat', 'w+')
Additionally manually opening and closing file handles is bad practice in python. The with statement handles the opening and closing of the resource automatically for you:
with open("myfile.dat", "w+") as f:
#doyourcalculations with the file object here
for line in f:
print line
All, thank you for your input. I was able to figure out that it was writing to the new file, but it was overwriting with the same text. The reason was because ".startswith" was returning false when I expected true. The misconception was due to the difference between how Windows and Unix treat new line characters (/n /r).
Since your code is running, there should be a file somewhere.
You call "PATH/script.py", but there is "/PATH/TextFile.txt" in your program. Is the slash before PATH a mistake? Have you checked the path in your program is really where you are looking for the output file?

Categories

Resources