how to create empty file in python [duplicate] - python

This question already has answers here:
Create empty file using python [duplicate]
(2 answers)
Closed 5 years ago.
I would like to create an empty file in Python. But I have difficulty creating one..Below is the Python code I used to create but it gives me error:
gdsfile = "/home/hha/temp.gds"
if not (os.path.isfile(gdsfile)):
os.system(touch gdsfile)
Error I got:
File "/home/hha/bin/test.py", line 29
os.system(touch gdsfile)
^
SyntaxError: invalid syntax
But from the command line, I am able to create new file using: touch
Thank you very much for your help
Howard

First you have a syntax error because os.system() expects a string argument and you have not provided one. This will fix your code:
os.system('touch {}'.format(gdsfile))
which constructs a string and passes it to os.system().
But a better way (in Python >= 3.3) is to simply open the file using the open() builtin:
gdsfile = "/home/hha/temp.gds"
try:
open(gdsfile, 'x')
except FileExistsError:
pass
This specifies mode x which means exclusive creation - the operation will fail if the file already exists, but create it if it does not.
This is safer than using os.path.isfile() followed by open() because it avoids the potential race condition where the file might be created by another process in between the check and the create.
If you are using Python 2, or an earlier version of Python 3, you can use os.open() to open the file with the exclusive flag.
import os
import errno
gdsfile = "/home/hha/temp.gds"
try:
os.close(os.open(gdsfile, os.O_CREAT|os.O_EXCL))
except OSError as exc:
if exc.errno != errno.EEXIST:
raise

Related

Reading in csv file error: sys.argv[1], IndexError: list index out of range [duplicate]

This question already has answers here:
What does "sys.argv[1]" mean? (What is sys.argv, and where does it come from?)
(9 answers)
Closed 6 months ago.
I'm having trouble figuring out how the program is supposed to read in the cvs file.
Here is the error:
Traceback (most recent call last):
File "/Users/myname/Desktop/sealsort/sealsort.py", line 9, in <module>
newm_path = sys.argv[1] #'./s18_new.csv'
IndexError: list index out of range
As noted in the link posted by mkrieger1, the sys.argv[1] is referencing the first command line argument.
So instead of running a command like this:
python program.py
You need to run it with three arguments like this:
python program.py /path/To/first.csv /path/To/second.csv /path/To/third.csv
Note: Line 5 gives a use example
python sealsort.py /path/to/newm/survey /path/to/retm/survey /path/to/school/doc
It seems you are trying to run this script on a macOS machine. And I'm supposing you have the three CSV files in the same folder as the Python script.
You need to navigate, via terminal, to the folder the files are stored. So, first open the Terminal application, then navigate to the folder with this command: cd /Users/myname/Desktop/sealsort (here I'm using the same path that is in your question), then you will need to execute the script as described in the first comments:
# USE LIKE:
# python sealsort.py /path/to/newm/survey /path/to/retm/survey /path/to/school/doc
Supposing the files are: s18_new.csv, s18_return.csv, s18_schools.csv, execute the script specifying the name of these files as arguments to the program. If you do not specify any of the required arguments, one of the elements at the indexes 1, 2, and 3 will not be found and you will get that error (IndexError: list index out of range).
So, the correct command would be: python sealsort.py ./s18_new.csv ./s18_return.csv ./s18_schools.csv
This way, the element at index 0 (of argv) will be sealsort.py, the element 1 will be s18_new.csv, 2 will be s18_return.csv, and 3 will be s18_schools.csv.
I hope this helps.

Cannot print data off a JSON file [duplicate]

This question already has answers here:
How should I write a Windows path in a Python string literal?
(5 answers)
Closed 6 months ago.
I have a JSON file called data.json and I am trying to print the data inside that JSON file. The JSON file got created by the command:
git log --pretty="format:{"commit":"%h", "merge":"%p", "author":"%an", "title":"%s", "body":"%b"}",>"C:\test_temp\data.json"
I am trying to print the data inside the file with the function parse_json but I am getting an error that says IOError: [Errno 22] invalid mode ('r') or filename "C:\test_temp\data.json"
json_directory = "C:\test_temp\data.json"
def parse_json_file(json_directory):
with open(json_directory) as f:
data = json.load(f)
print(data)
The json file is already there but I am not sure why it cannot read that file.
Also the data that got generate from the JSON file does not have proper formatting as the dictionary is not surrounded by the " " even though I indicated it in the executed git log command. Will that cause a problem if I try to parse the json file.
Maybe try:
json_directory = "C:\\test_temp\\data.json"
Your command is producing invalid json, so your json.load method call will never succeed.
You need to escape the quotes-- what you have supplied (as you can see from stack overflow's syntax highlighting) is actually a series of strings which your shell is concatenating together.
In BASH on OSX, escaping the strings looks like:
git log --pretty="format:{\"commit\":\"%h\", \"merge\":\"%p\", \"author\":\"%an\", \"title\":\"%s\", \"body\":\"%b\"}"
You could also enclose the entire argument to pretty with single quotes, as follows:
git log --pretty='format:{"commit":"%h", "merge":"%p", "author":"%an", "title":"%s", "body":"%b"}',>"C:\test_temp\data.json"
Once your json generation command is corrected, I suspect your script will succeed so long as the paths are correct.
If you try to correct the command as I have recommended and it does not work, please post the JSON file you are generating, as well as the shell you are using.

Python -How to solve OSError: [Errno 22] Invalid argument [duplicate]

This question already has answers here:
How should I write a Windows path in a Python string literal?
(5 answers)
Closed 6 months ago.
I am learning about file objects in python but whenever i try to open file it shows the following error.
I have already checked that file is in same directory and it exists
this error occurs only if i name my file as test if i use any other name then it works fine
here's my CODE
f = open('C:\\Users\Tanishq\Desktop\python tutorials\test.txt', 'r')
here's the ERROR
Traceback (most recent call last):
File "C:/Users/Tanishq/Desktop/question.py", line 1, in <module>
f = open('C:\\Users\Tanishq\Desktop\python tutorials\test.txt', 'r')
OSError: [Errno 22] Invalid argument: 'C:\\Users\\Tanishq\\Desktop\\python
tutorials\test.txt'
Your issue is with backslashing characters like \T :
Try:
f = open(r'C:\\Users\Tanishq\Desktop\python tutorials\test.txt', 'r')
Python uses \ to denote special characters. Therefore, the string you provided does not actually truly represent the correct filepath, since Python will interpret \Tanishq\ differently than the raw string itself. This is we we place the r in front of it. This lets Python know that we do indeed want to use the raw string and to treat \ as a normal character.

How to validate the syntax of a Python script? [duplicate]

This question already has answers here:
How can I check the syntax of Python script without executing it?
(9 answers)
Closed 6 years ago.
I just want the simplest possible way for my Python script to ask "is the Python code which I just generated syntactically valid Python?"
I tried:
try:
import py_compile
x = py_compile.compile(generatedScriptPath, doraise=True)
pass
except py_compile.PyCompileError, e:
print str(e)
pass
But even with a file containing invalid Python, the exception is not thrown and afterwards x == None.
There is no need to use py_compile. It's intended use is to write a bytecode file from the given source file. In fact it will fail if you don't have the permissions to write in the directory, and thus you could end up with some false negatives.
To just parse, and thus validate the syntax, you can use the ast module to parse the contents of the file, or directly call the compile built-in function.
import ast
def is_valid_python_file(fname):
with open(fname) as f:
contents = f.read()
try:
ast.parse(contents)
#or compile(contents, fname, 'exec', ast.PyCF_ONLY_AST)
return True
except SyntaxError:
return False
Be sure to not execute the file, since if you cannot trust its contents (and if you don't even know whether the file contains valid syntax I doubt you can actually trust the contents even if you generated them) you could end up executing malicious code.

How to Accept Command Line Arguments With Python Using < [duplicate]

This question already has answers here:
Python command line 'file input stream'
(3 answers)
Closed 8 years ago.
Is it possible to run a python script and feed in a file as an argument using <? For example, my script works as intended using the following command python scriptname.py input.txt and the following code stuffFile = open(sys.argv[1], 'r').
However, what I'm looking to do, if possible, is use this command line syntax: python scriptname.py < input.txt. Right now, running that command gives me only one argument, so I likely have to adjust my code in my script, but am not sure exactly how.
I have an automated system processing this command, so it needs to be exact. If that's possible with a Python script, I'd greatly appreciate some help!
< file is handled by the shell: the file doesn't get passed as an argument. Instead it becomes the standard input of your program, i.e., sys.stdin.
When you use the < operator in a shell you are actually opening the file and adding its contents to your scripts stdin
However there is is a python module that can do both. It's called fileinput.
https://docs.python.org/2/library/fileinput.html
It was shown in this post
How do you read from stdin in Python?
You can use the sys module's stdin attribute as a file like object.

Categories

Resources