I have my python code that runs a C++ code, which takes files in another folder as input.
I have my codes in folder A, and the input files are in folder B, and I have been trying this:
path = 'C:/pathToInputFiles'
dirs = os.listdir(path)
for path in dirs:
proc = subprocess.Popen([fullPathtoCppCode, inputFiles])
However, I keep receiving WindowsError: [Error 2] The system cannot find the file specified
The only way it works is when I put the C++ executable file in the same folder of the input files, which I am avoiding to do.
How can I make python reads the file path properly?
Try using os.path.join after your for statement.
path = os.path.join(directory, filename)
for example
def test(directory):
for filename in os.listdir(directory):
filename = os.path.join(directory, filename)
proc = subprocess.Popen([fullPathtoCppcode, inputFiles])
Related
I try to follow an example in an online course to create a function to change the files name by omitting the numbers from the files name. But I got this error:
os.rename(file_name, file_name.translate(None,"0123456789"))
WindowsError: [Error 2] The system cannot find the file specified
But the code runs fine on the video that I watched
import os
def rename_files():
# (1) get file naems from a folder
file_list = os.listdir(r"C:\prank")
#print (file_list)
saved_path = os.getcwd()
print (" Currnet Wroking Directory is " +saved_path)
os.chdir(r"C:\prank")
# (2) for each file, rename filename
for file_name in file_list:
os.rename(file_name, file_name.translate(None,"0123456789"))
os.chdir (saved_path)
rename_files()
Try this one out, there is no need to change the working directory, its not a good practice. Also if you are renaming files in C: you may have to execute the code as administrator.
import os
def rename_files():
# directoy with the files
directory=r"C:\prank"
# (1) get file names from a folder
file_list = os.listdir(directory) # this is the folder with the files
# (2) for each file, rename filename
for file_name in file_list:
new_name=''.join([s for s in file_name if s not in ['0','1','2','3','4','5','6','7','8','9']]) # remove numbers
os.rename(os.path.join(directory,file_name),os.path.join(directory,new_name))
rename_files()
I have the following function that gives me the list of files(complete path) in a given list of directories:
from os import walk
from os.path import join
# Returns a list of all the files in the list of directories passed
def get_files(directories = get_template_directories()):
files = []
for directory in directories:
for dir, dirnames, filenames in walk(directory):
for filename in filenames:
file_name = join(dir, filename)
files.append(file_name)
return files
I'am adding some files to the template directories in Django. But this function always return the same list of files even though some are added/deleted in the run time. These changes are reflected only when I do a server restart. Is that because of some caching that os.walk() performs or is it required that we need to restart the server after adding/removing some files ?
It is not django problem, your behaviour is result of python interpreter specific:
Default arguments may be provided as plain values or as the result of a function call, but this latter technique need a very big warning. Default values evaluated once at start application and never else.
I' m sure this code will solve your problem:
def get_files(directories = None):
if not directories:
directories = get_template_directories()
files = []
for directory in directories:
for dir, dirnames, filenames in walk(directory):
for filename in filenames:
file_name = join(dir, filename)
files.append(file_name)
return files
You can find same questions on Stackoverflow Default Values for function parameters in Python
I am trying to set up a program to put my minecraft server world into a zip and place it into another directory on another drive (/media/500gb/MinecraftWorldBackups)
But I keep getting this error
Although the folder doesn't contain a folder or file called 'h'
What do I need to do to fix this I believe it is due to file and folder?
#!/usr/bin/env python
import time, zipfile
while True:
FileName = 'MinecraftBackup_' + str(int(time.time()))
Path = '/home/bertie/Desktop/FeedTheBeastServer/world/'
print(FileName)
Zip = zipfile.ZipFile('/media/500gb/MinecraftWorldBackups/'+FileName+'.zip','w')
for each in Path:
print(each)
try: Zip.write(Path + each)
except IOError: None
Zip.Close()
print('Done')
time.sleep(60)
My problem is to read '.csv' files in catalogs and do some calculations on them.
I have calculations working but my for loop seem not to work as I want to.
d = 'F:\MArcin\Experiments\csvCollection\'
for dirname, dirs, files in os.walk(d):
for i in files:
if i.endswith('.csv'):
data1 = pd.read_csv(i, sep=",")
data = data1['x'][:, np.newaxis]
target = data1['y']
The error Iam getting is:
IOError: File 1.csv does not exist
files is list of all '.csv' files inside dirname
i is str of size 1 and contains 1.csv (that is first of the files in catalog)
Any ideas why this is not working?
Thanks for any help.
Because 1.csv is somewhere on the filesystem and when you call read_csv() it opens file relative to current directory.
Just open it using absolute path:
data1 = pd.read_csv(os.path.join(dirname, i), sep=",")
dirname in os.walk represents actual directory where file 1.csv is located.
I want to copy too long paths with python using shutil.copyfile.
Now I read this Copy a file with a too long path to another directory in Python page to get the solution. I used:
shutil.copyfile(r'\\\\?\\' + ErrFileName,testPath+"\\"+FilenameforCSV+"_lyrErrs"+timestrLyr+".csv")
to copy the file but it gives me an error : [Errno 2] No such file or directory: '\\\\?\\C:\\...
Can anyone please let me know how to incorporate longs paths with Shutil.copyfile, the method I used above should allow 32k characters inside a file path, but I cant even reach 1000 and it gives me this error.
Since the \\?\ prefix bypasses normal path processing, the path needs to be absolute, can only use backslash as the path separator, and has to be a UTF-16 string. In Python 2, use the u prefix to create a unicode string (UTF-16 on Windows).
shutil.copyfile opens the source file in 'rb' mode and destination file in 'wb' mode, and then copies from source to destination in 16 KiB chunks. Given a unicode path, Python 2 opens a file by calling the C runtime function _wfopen, which in turn calls the Windows wide-character API CreateFileW.
shutil.copyfile should work with long paths, assuming they're correctly formatted. If it's not working for you, I can't think of any way to "force" it to work.
Here's a Python 2 example that creates a 10-level tree of directories, each named u'a' * 255, and copies a file from the working directory into the leaf of the tree. The destination path is about 2600 characters, depending on your working directory.
#!python2
import os
import shutil
work = 'longpath_work'
if not os.path.exists(work):
os.mkdir(work)
os.chdir(work)
# create a text file to copy
if not os.path.exists('spam.txt'):
with open('spam.txt', 'w') as f:
f.write('spam spam spam')
# create 10-level tree of directories
name = u'a' * 255
base = u'\\'.join([u'\\\\?', os.getcwd(), name])
if os.path.exists(base):
shutil.rmtree(base)
rest = u'\\'.join([name] * 9)
path = u'\\'.join([base, rest])
os.makedirs(path)
print 'src directory listing (tree created)'
print os.listdir(u'.')
dest = u'\\'.join([path, u'spam.txt'])
shutil.copyfile(u'spam.txt', dest)
print '\ndest directory listing'
print os.listdir(path)
print '\ncopied file contents'
with open(dest) as f:
print f.read()
# Remove the tree, and verify that it's removed:
shutil.rmtree(base)
print '\nsrc directory listing (tree removed)'
print os.listdir(u'.')
Output (line wrapped):
src directory listing (tree created)
[u'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaa', u'spam.txt']
dest directory listing
[u'spam.txt']
copied file contents
spam spam spam
src directory listing (tree removed)
[u'spam.txt']