What is 'target' in 'target = open(...)' - python

I'm learning Python as someone more familiar with databases and ETL. I'm not sure where target comes from in the following code.
from sys import argv
script, filename = argv
target = open(filename, 'w')
I think argv is a class in the sys module, but I don't think target comes from argv.

If you run type(target), you will get this: <_io.TextIOWrapper name='dde-recommendation-engine/sample_data/synthetic-micro/ratings.txt' mode='r' encoding='UTF-8'>
What that means in simple terms is that it is an object accessing that particular file (with only write permission because you have a w mode).
You can use this object to add stuff into the file by target.write(.....)
Do remember to close the file however by doing target.close() at the end.
Another way to do the same and I prefer this most of the times is:
with open(filename, 'w') as target:
target.write(...)
This way the file is closed automatically once you are out of the with context.

argv is the list populated by the arguments provided by user while running the program from shell. Please see https://docs.python.org/3/library/sys.html#sys.argv for more info on that.
User supplied the filename from shell, program used the open call https://docs.python.org/3/library/functions.html#open to get a file handle on that filename
And that file handle is stored in variable called target (which could be named anything you like) so that you can process the file using other file methods.

You are using open() - a built-in function in python. This function returns an File object - which is assigned to target variable. Now you can interact with target to write data (since you are using the w mode)
.

Related

Using a file created in a keyword function as an argument

Confused on how to use a created file for a function in the robot framework. Normally I would do something along the lines of f = open("logFileTest.txt", "w") and then pass f into the function like so getAddresses(f)
This getAddresses function is written to use a passed argument for logging.
def getAddresses(logFile=None):
print("Entering getAddresses!", file=logFile)
So when translating this to the robot framework I attempt to create a file and set that created file into a variable and then call the function with that newly created variable.
${logFile}= Create File log.txt
${addresses}= Get Addresses ${logFile}
This however sets logFile equal to none rather than the newly created log.txt that I would like it to be set to.
Is there another way in the robot framework to open the file than Get File? Get file in this case doesn't work as it only returns the contents of the file.
Create File does not return path to the file (or anything according to documentation [1]). You could set path as variable and give that to Create File keyword as argument and then also to your Get Addresses keyword.
${path}= Set Variable log.txt
Create File ${path}
${addresses}= Get Addresses ${path}
Then in the keyword implementation you need to open it (as path is only passed):
def getAddresses(logFile):
with open(logFile, 'w') as f:
print('Entering getAddresses!', file=f)
[1] https://robotframework.org/robotframework/latest/libraries/OperatingSystem.html#Create%20File

Why is a Python exported file not closing?

When exporting a csv-file from Python, for some reason it does not close (even when using the 'with' statement) because when I'm calling it afterwards I get the following error:
PermissionError: [WinError 32] The process cannot access the file because it is being used
by another process
I suppose it has to be the close function that hangs, because when I'm printing behind the with statement or the close() statement, it gets printed (e.g. print fileName). Any suggestions that might solve this matter?
(Also when I'm trying to open the exported CSV-file, I get a read-only message because it's used by another program. I can access it properly only when Python is closed, which is just annoying)
import csv, numpy, os
import DyMat
import subprocess
os.chdir("C:/Users/myvhove/Documents/ResultsPyDymInt/Dymola/CoupledClutches")
dm = DyMat.DyMatFile("dymatresfile")
print(dm.names())
varList = ('J1.w', 'J2.w', 'J3.w', 'J4.w')
fileName = dm.fileName + '.csv'
with open(fileName, 'w', newline='') as oFile:
csvWriter = csv.writer(oFile)
vDict = dm.sortByBlocks(varList)
for vList in vDict.values():
vData = dm.getVarArray(vList)
vList.insert(0, dm._absc[0])
csvWriter.writerow(vList)
csvWriter.writerows(numpy.transpose(vData))
subprocess.call("dymatresfile.csv")
print(fileName)
The code is correct. The problem must be somewhere else.
Either another forgotten python process or as #CristiFati mentioned an open editor.
In the worst case restart the PC and call the python script directly after logging in again.
The error should no more be there.

Can't pass file handle to subprocess

I created a file in the current directory with echo "foo" > foo. I then tried to pass that file to subprocess.run, but I seem to misunderstand how file paths are handled in Python, since I'm getting an error. What's wrong?
My test code
with open('foo') as file:
import subprocess
subprocess.run(['cat',file])
yields
TypeError: expected str, bytes or os.PathLike object, not _io.TextIOWrapper
What is a PathLike object? How to I get it from open('foo')? Where can I find more information about how files are handled in Python?
There's no need to open the file in the first place. You can simply run
import subprocess
subprocess.run(['cat', 'foo'])
The cat command is being run as a shell command by your machine, so you should just be able to pass the file name as a string.
Python does not handle the file at all. The point of subprocess is to pass a command to the underlying system (in this case, apparently a UNIX based OS). All you are doing is passing a plaintext command to the command line.
I won't, however, discourage you from reading about file handling. Look at this documentation.
PathLike object: docs
How to get it from the open call's return value:
Use the name field
subprocess.run(['cat',file.name])
Learn about python files: Reading and writing files

How to invoke a Perl script that need args from Python

I'm writing my script in Python, and I want to invoke a Perl script from it.
This is the line I want to call:
perl conv_intel_hex_2_verilog.pl arg1 arg2
while arg1 is the input from the Python script and arg2 is a new file that I'm creating.
So far I have this:
def main(argv):
file = open("test.hex", "w")
input = argv[0];
subprocess.call(["perl", "conv_intel_hex_2_verilog.pl", input]);
file.close();
This runs and does nothing.
And when I'm changing the
subprocess.call(["perl", "conv_intel_hex_2_verilog.pl", input]);
to
subprocess.call(["perl", "conv_intel_hex_2_verilog.pl", input ,file]);
it doesn't compile...
As you've described it, the program you're running expects its second argument to be the name of a file, so that's what you need to give it. In your current code, you're giving it a Python file object, which is not the same as the string name of a file.
subprocess.call(["perl", "conv_intel_hex_2_verilog.pl", input, "test.hex"]);
There is no need to create the file object prior to running that code, either. The other program will surely create it for you, and might even balk if it finds that the file already exists.
You cannot just give it a filehandle (or whatever that is called in Python). You are constructing a call to another program, and that program expects a filename, so pass the filename as a string.
subprocess.call(["perl", "conv_intel_hex_2_verilog.pl", input ,"test.hex"]);
You also don't need to open the file first.

Opening file - Performing a function

I was wondering if someone could give me a direction on how to give functions to a file... This is a bit hard to explain, so I'll try my best.
Let's say I have an application (using wxPython) and let's say that I have a file. Now this file is assigned to open with the application. So, I double-click the file and it opens the application. Now my question is, what would have to be written on the file to, for example, open up a dialog? So we double-click the file and it opens a dialog on the application?
PS: I know that I have first to associate the program with a certain file type to double-click it, but thats not the question.
AFAIK most platforms just call the helper app with the file you clicked on as an argument, so your filepath will be in sys.argv[1]
I think what he wants to do is associate a file extension to his application so when he opens the file by double clicking it, it sends the contents of the file to his app; in this case, display the contents within a Dialog?
If this is the case, than the first thing you would need to do (provided you are on windows) is create the appropriate file association for your file extention. This can be done through the registry and when setup correctly will open your app with the the path/filename of the file that was executed as the first argument. Ideally it is the same as executing it from the command line like:
C:\your\application.exe "C:\The\Path\To\my.file"
Now as suggested above, you would then need to use sys.argv to to obtain the arguments passed to your application, in this case C:\Path\To\my.file would be the first argument. Simply put, sys.argv is a list of arguments passed to the application; in this case the first entry sys.argv[0] will always be the path to your application, and as mentioned above, sys.argv[1] would be the path to your custom file.
Example:
import sys
myFile = sys.argv[1]
f = file(myFile, "r")
contents = f.read()
f.close()
Then you will be able to pass the variable contents to your dialog to do whatever with.

Categories

Resources