2

I'm trying to save a file in a program while Python runs in the background. I made a while loop for "os" to try and find the Results file, and to keep checking until it exists. Before that (the try, except block), I made a short backup file code (I'm unsure if this is significant to my problem).

import os
import time

path = "D:\\DICOM\\Data\\"

try:
    os.rename(path + "Results.csv", path + "Archive\\Results-Backup1.csv")
except FileNotFoundError:
    print("")
except FileExistsError:
    os.remove(path + "Archive\\Results-Backup1.csv")
    os.rename(path + "Results.csv", path + "Archive\\Results-Backup1.csv")

path= path + "Results.csv"

k = str(os.path.isdir(path))

print(k)

while k== "False":

    time.sleep(1)

    k=str(os.path.isdir(path))

print("k is now TRUE")

I'm waiting for k to be True so I can continue with my code, but it's always False since os never recognizes the new path. Can anyone find any problems with my code?

Thank you in advanced very much :)

Alex Borg
  • 143
  • 2
  • 7

1 Answers1

0

You should avoid creating file paths as strings with separators and concatinating them using + operator.

Use os.path.join and pass list of directories.

import time
import shutil
import os

my_path = os.path.join('C:', os.sep, 'DICOM', 'Data')
from_path = os.path.join(my_path, "Results.csv")
to_path = os.path.join(my_path, "Archive", "Results-Backup1.csv")
try:
    shutil.move(from_path, to_path)
except FileNotFoundError:
    print("")

my_path = os.path.join(my_path, "Results.csv")

k = os.path.isfile(my_path)

print(k)

while not k:
    time.sleep(1)
    k = os.path.isfile(my_path)

print("k is now TRUE")

Make sure that your program is creating your file correctly.

domandinho
  • 1,260
  • 2
  • 16
  • 29
  • Thanks very much!!! This makes much more logical sense as well. I'd never have figured that out, thank you :) – Alex Borg Nov 11 '17 at 06:46
  • Just one question! Why did you use os.sep after the C:, but nowhere else in the script? Isn't it representative of "\\"? Does it not have to be after every folder? – Alex Borg Nov 11 '17 at 07:14
  • My answer based second answer of this question: https://stackoverflow.com/questions/2422798/python-os-path-join-on-windows It is used in one place where my_path is initialized because other plases are joining my_path variable – domandinho Nov 11 '17 at 13:00