I'm trying to code a program with Python 3.7.2 that takes values out of one XML file and copys it into another XML file.
With my current code this only works with 1 file in a folder but I need it to also work with multiple files in one directory. Right now when executing my code, I get the following error in VS-Code:
FileNotFoundError: [Errno 2] No such file or directory: 'H:\\app_python/in_spsh/ZAA.S0333055.500.CCT.000000153774.O.0001ZAA.S0444055.500.CCT.000000153774.O.0001'
This is due to me having two files in the same directory. In this case 'ZAA.S0444055.500.CCT.000000153774.O.0001' and 'ZAA.S0333055.500.CCT.000000153774.O.0001'
I'm using fnmatch.filter to set the name of a file as a string, but with my current code this won't work with multiple files.
Here is my code:
import shutil
import os
import time
import fnmatch
import copy
from xml.etree import ElementTree as ET
import datetime
import sys
dt = datetime.datetime.now().strftime("%Y/%m/%d %H-%M-%S")
sys.stdout = open('H:\\app_python/log/log.txt', 'w+')
while len(os.listdir('H:\\app_python/in_spsh/')) == 0:
print("{} > No file found in 'in_spsh'. Sleeping...".format(dt))
time.sleep(5)
else:
filename_old = fnmatch.filter(os.listdir('H:\\app_python/in_spsh/'), 'ZAA.*.0001')
filename_string = ''.join(filename_old)
print("{} > File '{}' acquired".format(dt, filename_string))
Does any1 know what I need to change in order to make this code work with multiple files?
Related
I was making a project that has you type what's on the screen, and I was trying to get it to generate random words from a file. but I got an error saying FileNotFoundError: [Errno 2] No such file or directory: 'words.txt'. I double-checked that the file was in the same directory and it was named right. Then I went back to my other program using this file, and it didn't work either (Even though it worked perfectly before). I tried using a shorter file to see if that was the problem, but it still gave me the same error.
Here is my (incomplete) code:
from Tkinter import Tk, Entry
import random
words = open('words.txt')
tab = Tk()
words = words.readlines()
totype = words[random.randint(1, len(words))]
print(totype)
How can I fix this?
Check that the directory you're running python from is the correct directory.
On python 3.4+, you can use the pathlib module to open files in the same directory as the script easily:
from pathlib import Path
p = Path(__file__).with_name('file.txt')
with p.open('r') as f:
words = f.read()
You can check this with:
import os
cwd = os.getcwd()
And use the relative directory from that.
Alternatively, use the full directory.
You can get the full path of the script using:
import os
dir_path = os.path.dirname(os.path.realpath(__file__))
Then you can use dir_path + file_name to get your full file path.
You have to give directory path specifying where the file is located if the file is located in same directory as your script file you can do
from Tkinter import Tk, Entry
import random
words = open('./words.txt')
tab = Tk()
words = words.readlines()
totype = words[random.randint(1, len(words))]
print(totype)
if it is located in some other folder then you can do
file = open(r'C:\Users\Directory\sample.txt') #example
words = open(file)
tab = Tk()
words = words.readlines()
totype = words[random.randint(1, len(words))]
print(totype)
I am trying to open a file inside the two folders
import glob
import os
wPlayer = '1'
playeritems = 'PlayerFiles/PlayerItems'
with glob.glob(os.path.join(playeritems, open('inventory.%s.txt' % wPlayer, 'r'))) as wPs:
#do stuff with wPs
But it is giving me there error
There is no such file or directory: 'inventory.1.txt'
But I know for a fact that there is 'inventory.1.txt' inside PlayerFiles/PlayerItems.
What am I doing wrong? Is it because it is a string?
I used this question to get where I am now.
If you have the path and the filename, as constructed with your join, what is glob doing there? It looks like you're opening a single file.
import os
wPlayer = '1'
playeritems = 'PlayerFiles/PlayerItems'
with open(os.path.join(playeritems,'inventory.%s.txt' % wPlayer), 'r') as wPs:
#do stuff with wPs
We download GPX files from email, and I'd like to run a script where it selects the GPX and says whether it's there or just adds the GPX into another file.
I have a script where it adds the GPX into a file but then I need it to check if it was already in the file and to warn us and this part in the script doesn't work.
import glob
import os.path
import shutil
SRC_DIR = 'C:/Work'
TARG_DIR = 'C:/Work/GPS_N32'
GLOB_PARMS = "*.gpx"
for file in glob.glob(os.path.join(SRC_DIR, GLOB_PARMS)):
if file not in glob.glob(os.path.join(TARG_DIR, GLOB_PARMS)):
shutil.copy(file,TARG_DIR)
else:
print("{} exists in {}".format(
file,os.path.join(os.path.split(TARG_DIR)[-2:])))
The error message should read this gpx is already there! And if the gpx is not there then a message should say added files.
import glob
import os.path
import shutil
SRC_DIR = r"C:\Work"
TARG_DIR = r"G:\GPS\_in\Trimble\GPS_NEW"
GLOB_PARMS = "*.gpx"
os.chdir(SRC_DIR)
for gpxfile in glob.glob(GLOB_PARMS):
if os.path.exists(os.path.join(TARG_DIR, gpxfile)):
print("{} already exists in {}".format(gpxfile, TARG_DIR))
else:
shutil.copy(gpxfile, TARG_DIR)
I'm having an issue figuring out how can i implement a function to overcome my problem.
My code works fine, but the fault is that sometimes i need more than just one file.
import os
import shutil
target_dir = 'C:\DIST\WR_4.5\Test'
pass_text = 'Test End'
def check_and_copy():
log = open('C:\DIST\WR_4.5\oHistory2.log')
for line in log:
if pass_text in line:
name = '\kp.log'
else:
name = '\kf.log'
if not os.path.exists(target_dir):
os.makedirs(target_dir)
shutil.copy2('C:\DIST\WR_4.5\oHistory2.log', target_dir+name)
else:
os.chdir(target_dir)
shutil.copy2('C:\DIST\WR_4.5\oHistory2.log', target_dir+name)
What i'd like to accomplish is to be able to copy multiple instances of files with or without shutil. The filename is determined by the code itself as you can see.
Thanks for the help in advance.
I have a Python script and I'm trying to delete all files in this directory EXCEPT for the .csv file. Getting syntax error on the "not" in this line:
for CleanUp not in glob.glob("c:\python\AIO*.*"):
If I remove the "not", it will delete the AIO.csv file, but I need to preserve that file and ONLY that file. Not clear why it's not working.
import os
import glob
import time
file_path = "c:\python\AIO.csv"
while not os.path.exists(file_path):
time.sleep(10)
if os.path.isfile(file_path):
#Verifies CSV file was created, then deletes unneeded files.
for CleanUp not in glob.glob("c:\python\AIO*.*"):
os.remove(CleanUp)
Try this instead
import os
import glob
import time
file_path = "c:\python\AIO.csv"
while not os.path.exists(file_path):
time.sleep(10)
if os.path.isfile(file_path):
# Verifies CSV file was created, then deletes unneeded files.
for clean_up in glob.glob('C:/python/*.*'):
print(clean_up)
if not clean_up.endswith('AIO.csv'):
os.remove(clean_up)
glob doesn't print any directories, only files, and it also gets the entire path so you can just call os.remove(clean_up). This should work. It works on my machine which is also Windows 7 x64.
I think your problem was that you were looping over the path c:\python\AIO*.* which is a file so it only does one loop and terminates which skips all other files in the directory
An alternate way would be get the list of files (glob.glob returns a list) and then remove the one item you want to preserve.
import os
import glob
import time
file_path = "c:\python\AIO.csv"
while not os.path.exists(file_path):
time.sleep(10)
if os.path.isfile(file_path):
# get list of files that match
cleanupFiles = glob.glob("c:\python\AIO*.*")
cleanupFiles.remove(file_path)
for cleanupFile in cleanupFiles:
os.remove(cleanupFile)