A Python script is executed by a QProcess. Within this script, a specific file should be opened and written to. The file path should always be \\127.0.0.1\folder\myfile.json
.
def write_to_json(IP, slice_id, json_lines):
#IP = "127.0.0.1" (or any other network id as str)
#slice_id = 1
#json_lines: string
output_file = r"\\{}\hatches\slice{}.json".format(IP, slice_id)
subprocess.run(f"echo. >> {output_file}", shell=True)
with open(output_file, "a") as f: #also tried w
for line in json_lines:
f.write(line + '\n')
When this code is being executed by an IDE, it works fine and the Path can be found. When run using QProcess, the file system seems to add random backslashes so the path cannot be found:
[Errno 2] No such file or directory: '\\\\127.0.0.1\\hatches\\slice1.json'
Other approaches were also tried (apart from parsing to the file using subprocess, since the length of each line could be greater than 48k elements, which exceeds the max length of the enabled path length in Windows. Otherwise parsing the input to the file using subprocess would have worked):
passing the path as
output_file = r"{}\hatches\slice{}.json".format(IP, slice_id)
output:
[Errno 2] No such file or directory: '127.0.0.1\\hatches\\slice1.json'
removing the backslashes leads to:
output_file.remove(r"\\","")
output: [Errno 2] Could not connect to network '127.0.0.1hatchesslice1.json'
Does anyone have any idea how to solve this backslash problem? (The synax cannot be changed, otherwise no connection can be made).
The solution was to give the network path (e.g. \27.0.0.1\folder) a drive name, e.g. "M:/" so any slashes can be used for accessing it.