0

I'm trying to access/modify a file from a python script. Right now, I have this:

outfile = open("file.txt","a")
outfile.write("something")
outfile.write("something else")
outfile.close()

Is there any way to access file.txt if it's located on another computer?

Edit: turns out I will be able to import the text file to the local computer, so problem solved, I guess!

  • In order to answer your question we need more details on how the file is made available. Web server, networked file system, remote login, something else? – timgeb Feb 21 '22 at 10:58

1 Answers1

0

Yes, there is.

  1. Download the remote file temporarily to the local computer where your Python code is located with SCP.
  2. Modify it.
  3. Upload the modified file to the remote with SCP.

Step 1: Download the remote file

scp -i ~/.ssh/the-ssh-key remoteusername@remote-ip:/remote-location/remote-file.txt /local-location/local-file.txt

Step 2: After modifying the file, upload it to the remote.

scp /local-location/local-file.txt -i ~/.ssh/the-ssh-key remoteusername@remote-ip:/remote-location/remote-file.txt

Then you can delete the temporary local file if you want.

If you want to create a new file on the remote:

  1. Create the file in the local computer where your Python is located.

  2. Create the file.

  3. Upload the created file to the remote with SCP.

    scp /local-location/local-file.txt -i ~/.ssh/the-ssh-key remoteusername@remote-ip:/remote-location/remote-file.txt

If you want to access the remote with a password instead of an ssh key or to learn more about the usage of SCP, you can follow the instructions here:

https://linuxize.com/post/how-to-use-scp-command-to-securely-transfer-files/

ALTERNATIVE METHOD

Instead of using a pure SCP command, you can prefer subprocess in python.

import subprocess
subprocess.run(["scp", FILE, "USER@SERVER:PATH"])
#e.g. subprocess.run(["scp", "foo.bar", "joe@srvr.net:/path/to/foo.bar"])

Source: https://stackoverflow.com/a/68365/15529570

ce7in
  • 31
  • 4