Getting error in this python code while printing renamed files - python

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.

Related

Python Os Changing Path

I'm trying to change directory when calling a python file in cmd but it's not working !
I tried all types of slashes & back slashes & escaping, sometimes when the code runs, the directory isn't changing and stays the same where i start the py file and sometimes the code isn't running and i have this error Error
import os
#import sys
os.chdir('%SystemRoot%/Users/%username%/AppData/Local/Google/Chrome/User Data')
os.system('cd \"%SystemRoot%\\Users\\%username%\\AppData\\Local\\Google\\Chrome\\User Data\"')
I tried to change the system variables %SystemRoot% and %username% to words like C:/ and user2 (my system root and user name ) but still not working !
Can anyone try it in his computer and tell me what to change pls ?
Thanks !
Python does not automatically expand shell variables like %SystemRoot% and %username% to their actual values, this is what caused the error you were getting. Try os.chdir(os.path.expandvars(os.path.expanduser('%SystemRoot%/Users/%username%/AppData/Local/Google/Chrome/User Data'))) for the first line as this should expand the %username% and %SystemRoot% variables to a valid path.
EDIT: Sorry, I misunderstood your question. While this will take care of the error you were getting, you cannot change the shell's working directory from your script; see comment under your question by Ulrich Eckhardt

Indentation and Syntax Errors in File Organizing Script in 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.

file_object.read() evaluates to empty string in python 3

So, I am creating an app that needs to make use of files in python. I watched 10000 youtube videos, and I got this from what I watched
with open(str(fileName)) as foil: # to read
notes = foil.read().splitlines()
with open("notes.txt", "a") as foil: # to add
print(toAdd, file=foil)
But when I do print(notes.splitlines()[0]), My program always prints an empty string.
I did a check to change it to something if it is blank
if notes.splitLines()[0] == "": notes = "The note was empty"
Why is this happening? Thanks in advance to anybody that awnsers.
PS: Where do these files go? Do I need to replace "notes.txt" with a file path for it to work?
PPS: There is no syntax errors in my program. If there is one in my code in this post, I simply got it wrong when typing it into this post.
Your code raises an exception (AttributeError) for me. In general, notes will be a list of the lines in your source file - if the source file is empty, this should also raise an error as the list index will be out of range.
In general, your filename needs to be the path that your program needs to find the file. If they are in the same directory, something like 'file.txt' will be enough. If not, you will have to provide the full path, or it will result in a FileNotFoundError. Hope this clears up your questions.

Confusing problem >> FileNotFoundError: [Errno 2] No such file or directory:

This problem puzzled me.
Maybe the problem is in the code, I hope you take a look
with open(training_images_labels_path,'r') as file:
lines = file.readlines()
He says that the file does not exist
FileNotFoundError: [Errno 2] No such file or directory: '\\Desktop\\project\\data\\generated\\training_images_labels.txt'
Though the file exists
I need solutions
If it says that the file does not exist though the file exists, it means the path has been not given properly. Try giving the path correctly.
Method 1:
Giving correct path 'C:\\Users\\Public\\Desktop\\project\\data\\generated\\training_images_labels.txt' or
'C:\\Users\\<insert your username>\\Desktop\\project\\data\\generated\\training_images_labels.txt' is your path if I guess correctly
Method 2:
Using os module ( Recommended )
mydir = 'C:/Users/Public/Desktop/project/data/generated'
myfile = 'training_images_labels.txt'
training_images_labels_path = os.path.join(mydir, myfile)
with open(training_images_labels_path,'r') as file:
lines = file.readlines()
Method 3:
You can also try changing the working directory to the location where your data is present. ie Desktop>project>data>generated here and open the file with file name. ie
with open('training_images_labels.txt','r') as file:
lines = file.readlines()
I had the same problem with importing an excel file, which of course exists in the same directory with my .py file. The chosen solution above did not help me, and actually I didn't understand those three methods, as I am working on mac OS.
This method worked for me: in Spyder, I usually run the file by pressing the keys "Shift + Enter", which in this case made the problem. So, my solution was, to press on the "Run file" button (or the fn+F5 key) instead.
Maybe someone wants to explain the difference.
Looks like its a windows path you are working and i believe path really thrown in the error is wrong when compared to the actual where the txt file resides.. just cross check once, if that's the case try to pass the correct path in to the variable "training_images_labels_path"
Can you tell how you created this path.Some advise.
use path separator library to generate path to avoid this error.
training_images_labels_path
further try to navigate parent directory using python and print pth.may be some new line or linux/windwos convereted path or other special character in path. navigating parent directory and listing will solve
if still not solve try to navigatep parent-parent dir and print path
try hard
Watch your path if its correct or not. I had the same problem and it turned out i didnt had the good path set

Safe way to read directory in Python

try:
directoryListing = os.listdir(inputDirectory)
#other code goes here, it iterates through the list of files in the directory
except WindowsError as winErr:
print("Directory error: " + str((winErr)))
This works fine, and I have tested that it doesnt choke and die when the directory doesn't exist, but I was reading in a Python book that I should be using "with" when opening files. Is there a preferred way to do what I am doing?
You are perfectly fine. The os.listdir function does not open files, so ultimately you are alright. You would use the with statement when reading a text file or similar.
an example of a with statement:
with open('yourtextfile.txt') as file: #this is like file=open('yourtextfile.txt')
lines=file.readlines() #read all the lines in the file
#when the code executed in the with statement is done, the file is automatically closed, which is why most people use this (no need for .close()).
What you are doing is fine. With is indeed the preferred way for opening files, but listdir is perfectly acceptable for just reading the directory.

Categories

Resources