Повторно не могу обратиться к файлу
у меня такая проблема всплыла. Программа представляет из себя простой клиент - сервер. После того как сервер получает дату от клиента, он сохраняет файл с именем tempFile, когда приходят следующие данные файл перезаписывается. Затем парсит, определяет что это за файл, организовывает каскад папок, и в последнюю папку копирует временный файл. В итоге, в первый раз все отрабатывает так как нужно, но когда приходят следующие данные вылетает ошибка :
Traceback (most recent call last):
File "C:\Users\Администратор\AppData\Local\Programs\Python\Python39\lib\shutil.py", line 806, in move
os.rename(src, real_dst)
FileNotFoundError: [WinError 3] Системе не удается найти указанный путь: 'output/tempFille.txt' -> 'C:\\Program Files (x86)\\Client-server_V.1.1\\Database\\29\\2021\\06\\17\\10-28/_S!.txt'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Program Files (x86)\Client-server_V.1.1\main.py", line 176, in <module>
newthread.run()
File "C:\Program Files (x86)\Client-server_V.1.1\main.py", line 140, in run
a.run()
File "C:\Program Files (x86)\Client-server_V.1.1\main.py", line 99, in run
shutil.move("output/tempFille.txt",hourPath +'/'+'_S!'+".txt")
File "C:\Users\Администратор\AppData\Local\Programs\Python\Python39\lib\shutil.py", line 820, in move
copy_function(src, real_dst)
File "C:\Users\Администратор\AppData\Local\Programs\Python\Python39\lib\shutil.py", line 435, in copy2
copyfile(src, dst, follow_symlinks=follow_symlinks)
File "C:\Users\Администратор\AppData\Local\Programs\Python\Python39\lib\shutil.py", line 264, in copyfile
with open(src, 'rb') as fsrc, open(dst, 'wb') as fdst:
FileNotFoundError: [Errno 2] No such file or directory: 'output/tempFille.txt'
Process finished with exit code 1
если открыть папку с этим временным файлам то он там есть. Почему то питон его не находит. пробовал ставить задержки, все равно не находит. Не понимаю с чем это связана, и куда копать.
Вот код
import socket
from threading import Thread
import os
import shutil
import glob
import sys
import datetime
import time
from datetime import datetime
# from openyfail.timr import now
from datetime import date
TCP_IP = ''
TCP_PORT = 9001
BUFFER_SIZE = 1024
Path = r'C:\Program Files (x86)\Client-server_V.1.1'
count = 0
swit = 0
class tempcopy():
def __init__(self, line):
self.line = line
def run(self):
print("tempcopy_run")
# adding tempfile tj strain folder
list_of_files=[]
print(self.line[10:12])
if self.line[10:12] == "30":
os.chdir(r"C:\Program Files (x86)\Client-server_V.1.1\Database\29")
list_of_files = glob.glob("*\*\*\*")
print(list_of_files)
if self.line[10:12] == "32":
os.chdir(r"C:\Program Files (x86)\Client-server_V.1.1\Database\31")
list_of_files = glob.glob("*\*\*\*")
if list_of_files:
latest_file = max(list_of_files, key=os.path.getctime)
print(latest_file)
"""rewriting file"""
time.sleep(1)
shutil.copy(r"C:\Program Files (x86)\Client-server_V.1.1\output"+"/"+"tempFille.txt",latest_file + '/'+ '_T!' + ".txt")
class addFolder():
def __init__(self, data,count):
self.data = data
self.count=count
def run(self):
# print('1111111111111111111')
print(self.data)
print('2222222222222')
PathData = os.path.join(Path, 'Database')
if not os.path.exists(PathData):
os.mkdir(PathData)
print(PathData)
ID_Path = os.path.join(PathData, self.data[10:12])
if not os.path.exists(ID_Path):
os.mkdir(ID_Path)
print(ID_Path)
now = datetime.now()
year = now.strftime("%Y")
yearPath = os.path.join(ID_Path, year)
if not os.path.exists(yearPath):
os.mkdir(yearPath)
print(yearPath)
month = now.strftime("%m")
monthPath = os.path.join(yearPath, month)
if not os.path.exists(monthPath):
os.mkdir(monthPath)
print(monthPath)
day = now.strftime("%d")
dayPath = os.path.join(monthPath, day)
if not os.path.exists(dayPath):
os.mkdir(dayPath)
print(dayPath)
hour = now.strftime("%H-%M")
hourPath = os.path.join(dayPath, hour)
os.mkdir(hourPath)
print(hourPath)
time.sleep(2)
# shutil.move("output/tempFille.txt",hourPath +'/'+year+month+day+hour+dot+minute+'_S!'+".txt")
shutil.copy("output/tempFille.txt",hourPath +'/'+'_S!'+".txt")
# os.remove("output/tempFille.txt")
# print(hourPath +'/'+year+month+day+hour+dot+minute+'.'+"txt")
class ClientThread():
def __init__(self, ip, port, sock, count):
self.ip = ip
self.port = port
self.sock = sock
self.count = count
print(" New thread started for " + ip + ":" + str(port))
def run(self):
with open(os.path.join(r"C:\Program Files (x86)\Client-server_V.1.1\output", 'tempFille' + '.txt'), 'w') as f:
while True:
data = self.sock.recv(1024).decode("utf-8")
if not data:
f.close()
print("++++++++++++++")
break
line = data.strip()
f.write(line)
self.sock.close()
print("___________________________________")
time.sleep(5)
word_strain_1 = 'Sensor ID 29'
word_strain_2 = 'Sensor ID 31'
word_temp_1 = 'Sensor ID 30'
word_temp_2 = 'Sensor ID 32'
print(os.path.isfile(r"C:\Program Files (x86)\Client-server_V.1.1\output\tempFille.txt"))
l = open(r"C:\Program Files (x86)\Client-server_V.1.1\output\tempFille.txt", "r")
for line in l:
if not line.find(word_strain_1):
print("strein_1")
l.close()
a=addFolder(word_strain_1,self.count)
a.run()
break
# addFolder(word_strain_1)
elif not line.find(word_strain_2):
print("Strain_2")
l.close()
a = addFolder(word_strain_2,self.count)
a.run()
break
# addFolder()
elif not line.find(word_temp_1):
l.close()
print("temp_1")
b=tempcopy(word_temp_1)
b.run()
break
elif not line.find(word_temp_2):
print("temp_2")
l.close()
b=tempcopy(word_temp_2)
b.run()
break
time.sleep(2)
tcpsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
tcpsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
tcpsock.bind((TCP_IP, TCP_PORT))
threads = []
while True:
tcpsock.listen(5)
print("Waiting for incoming connections...")
(conn, (ip, port)) = tcpsock.accept()
print('Got connection from ', (ip, port))
count = count + 1
newthread = ClientThread(ip, port, conn, count)
newthread.run()
print(count)