Indentation and Syntax Errors in File Organizing Script in Python - python

I've been working on a file organizing script from a tutorial: https://www.youtube.com/watch?v=MRuq3SRXses&t=22s
However, I'm new to python, so much of its nuance is hidden to me.
I have two indentation errors, as well as two syntax errors, however after looking at several questions on here, I still can't seem to fix it.
I'm confident I did not mix spaces and tabs, and the person from the tutorial I used seem to use his version of the script perfectly fine.
As for the syntax errors, I do not know what the issue could be.
Here is a copy of my code:
import os
import shutil
origin_dir = r'D:\TTITF\Game Files and Animations\Animations\Bridges\Walk ~ Alvie - V_2 R RAW'
target_dir = r'D:\TTITF\Game Files and Animations\Animations\Bridges\Walk ~ Alvie - V_2 R TRIMMED'
for f in os.listdir(origin_dir):
filename, file_ext = os.path.splitext(f)
try:
if not file_ext:
pass
elif int(filename) in range(0, 60):
shutil.move(
os.path.join(origin_dir, f'{filename}{file_ext}')
os.path.join(target_dir, 'V_O to V_4', f'{filename}{file_ext}'))
except (FileNotFoundError, PermissionError):
pass

You need to run the python code on IDE such as VS code,Jupyter notebook, Pycharm ( which is mentioned in tutorial that you are watching). Most developer write code in
When you are typing in the terminal you need to type keep and give space keeping in mind the indentation needed for the code
Useful commands to write in terminal
Press enter -> To enter a new line
Double press enter -> To execute the code

In the image on the left, you're typing your code into an interactive shell, which has some limitations. In particular, if you're entering a multiline construct such as a try/except block or an if/else block, you can't use any blank lines, otherwise the interpreter thinks the block is finished.
In the image on the right, you're typing your code at a command prompt, which is just wrong.

Related

Script failing to create a text file on code run

I have come across a very strange issue, I am using miniconda to test out the GPT-NEO ai text generator, I would call it like this in the command prompt:
C:\tools\miniconda3\python C:\Users\Graham\Desktop\Files\programming\Languages\Python\gpt_neo_app\ai.py
Python Code:
from os import system
from transformers import pipeline
import json
try:
# generator = pipeline('text-generation', model='EleutherAI/gpt-neo-2.7B', device=-1)
generator = pipeline('text-generation', model='EleutherAI/gpt-neo-1.3B', device=-1)
outjson = generator("unlock your hip flexors", do_sample=True, max_length=500, temperature=1.9)
outtext = json.loads(json.dumps(outjson[0]))["generated_text"]
# with open(r"C:\Users\Graham\Desktop\Files\programming\Languages\Python\gpttext.txt", "w") as f:
with open("gpttext.txt", "w") as f:
f.write(outtext)
print(outtext)
except Exception:
pass
The part that fails is writing to the .txt file, no matter what i do (even commenting out the text generation code and just putting in a random string to be written) the .txt file is never created or written to.
The text generator is working fine, i even tried the full path to the .txt file this still never worked, such a basic issue i cannot seem to see the problem, is there anything i have missed or have done wrong? it seems fairly straight forward enough but it just will not be created.
Any help would be appreciated.
Just posting incase anyone else has this issue, I needed to put the full path to the .txt file.

Getting error in this python code while printing renamed files

It is a code to rename all the files in a given directory but it seems while running in my terminal it giving me a syntax error at the print statement. Also if I comment the statement I get an error at the if statement of main. If I remove that too I get an error at the rename_files() function call statement.
import os
def rename_files():
#Get all the files from directory
file_list = os.listdir("/Users/arpitgarg/test")
print file_list
#Rename all the files.
for file_name in file_list:
os.rename(file_name, file_name.translate(None, "0123456789")
print file_name
if __name__ == '__main__':
rename_files()
I doubt the trace back error is 'can't find the file specified', if so your py script needs to know where the files to rename; cause its not in the current working directory.
You'll have to add:
os.chdir('the exact path to files to be renamed')
before the for loop
The file_names function does not contain a properly indented statement . Neither does the if name=='main' conditional. Also, the os.rename function call is missing a closing parenthesis . Try using a IDE next time , like pyCharm. It will highlight these syntax errors to you.
When asking for help, provide us with the necessary information to help.. in this case the actual Traceback.
As stated before, the indentation is one major error. Python uses whitespace to differentiate code blocks. http://en.wikipedia.org/wiki/Python_syntax_and_semantics#Indentation
I recommend using PyCharm, as also stated before, but it is a memory hog. If running on an older computer, I would recommend using Notepad++ or PyScripter.

Python code not writing to file unless run in interpreter

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.

Dropping a file onto a python script in windows - avoid Windows use of backslashes in the argument

I know all about how Windows uses backslashes for filenames, etc., and Unix uses forward. However, I never use backslashes with strings I create in my code. However:
When windows explorer "drops" a file onto a python script, the string it passes contains backslashes. These translate into escape sequences in the strings in the sys.argv list and then I have no way to change them after that (open to suggestions there)
Is there any way I can somehow make windows pass a literal string or ... any other way I can solve this problem?
I'd love my script to be droppable, but the only thing preventing me is windows backslashes.
EDIT:
Sorry everyone, the error was actually not the passing of the string - as someone has pointed out below, but this could still help someone else:
Make sure you use absolute path names because when the Windows shell will NOT run the script in the current directory as you would from a command line. This causes permission denied errors when attempting to write to single-part path-names that aren't absolute.
Cannot reproduce. This:
import os, sys
print sys.argv
print map(os.path.exists, sys.argv)
raw_input()
gives me this:
['D:\\workspaces\\generic\\SO_Python\\9266551.py', 'D:\\workspaces\\generic\\SO_Python\\9254991.py']
[True, True]
after dropping the second file onto the first one. Python 2.7.2 (on Windows). Can you try this code out?

Bash Variable Contains '\r' - Carriage Return Causing Problems in my Script

I have a bash script (rsync.sh) that works fine and has this line in it:
python /path/to/rsync_script.py $EMAIL "$RSYNC $PATH1 $PATH1_BACKUP"
I want to break the command (it's actually much longer than shown here because my variables have longer names) in two and use something like this:
python /path/to/rsync_script.py \
$EMAIL "$RSYNC $PATH1 $PATH1_BACKUP"
But when I do this I get the error:
scripts/rsync.sh: line 32: $'admin#mydomain.com\r': command not found
It puts the carriage return, \r in there.
How can I break this line up and not include the carriage return?
The problem looks like Windows line endings.
Here's how you can check in Python.
repr(open('rsync.sh', 'rb').read())
# If you see any \\r\\n, it's windows
Here's how you can fix it:
text = open('rsync.sh', 'r').read().replace('\r\n', '\n')
open('rsync.sh', 'wb').write(text)
Edit
Here's some code that shows the problem.
# Python:
open('abc-n.sh', 'wb').write('echo abc \\' + '\n' + 'def')
open('abc-r-n.sh', 'wb').write('echo abc \\' + '\r\n' + 'def')
And then run the files we made...
$ sh abc-n.sh
abc def
$ sh abc-r-n.sh
abc
abc-r-n.sh: 2: def: not found
If you can chnage the python script, maybe it will be easier to pass it the variable names thenselves, instead of their content.
From within the Python code you w=have better and more consistent tools to deal with whitespace characters (like \r) than from within bash.
To do that, just change your .sh line to
python /path/to/rsync_script.py EMAIL "RSYNC PATH1 PATH1_BACKUP"
And on your rsync_script.py, use os.environ to read the contents of the shell variables (and clear the \r's in them) - something like:
import os, sys
paths = []
for var_name in sys.argv(2).split(" "):
paths.append(os.environ[var_name].strip())
So I figured it out... I made a mistake in this question and I got so much awesome help but it was me doing a dumb thing that caused the problem. As I mentioned above, I may have copied and pasted from Windows at some point (I had forgotten since I did most of the edits in vim). I went back and wrote a short script with the essentials of the original in vim and then added in the '\' for line break and the script worked just fine. I feel bad accepting my own answer since it was so stupid. I made sure to up-vote everyone who helped me. Thanks again.

Categories

Resources