如何用Python将文件写入并保存到同网络另一机器?DHT11脚本存文件失败求助
Hey there! Let's troubleshoot why your DHT11 sensor script can't write data to another PC using open(). The core issue here is that Python's built-in open() only works with local file paths—you can't point it directly at a remote machine's path and expect it to work. Below are the most practical solutions tailored to your Raspberry Pi setup:
Solution 1: Mount a Remote Shared Folder (SMB/CIFS)
This is great if your target PC is running Windows (which uses SMB by default) or a Linux/macOS machine with SMB enabled. It lets you treat the remote folder like a local directory.
Set up the shared folder on the target PC:
- On Windows: Right-click the folder → Properties → Sharing → Enable sharing and grant read/write permissions to your user. Note the network path (e.g.,
\\192.168.1.100\SensorData). - On Linux: Install Samba (
sudo apt install samba), then configure a shared directory in/etc/samba/smb.confwith write permissions.
- On Windows: Right-click the folder → Properties → Sharing → Enable sharing and grant read/write permissions to your user. Note the network path (e.g.,
Prepare your Raspberry Pi:
Install the tools to mount SMB shares:sudo apt-get update && sudo apt-get install cifs-utilsCreate a local mount point:
sudo mkdir /mnt/remote_sensor_dataMount the remote share:
Replace the placeholders with your target PC's details:# For Windows shares sudo mount -t cifs //192.168.1.100/SensorData /mnt/remote_sensor_data -o username=YourWindowsUser,password=YourWindowsPass,vers=3.0 # For Linux Samba shares sudo mount -t cifs //192.168.1.100/sensor_data /mnt/remote_sensor_data -o username=YourSambaUser,password=YourSambaPassUpdate your Python script:
Now you can write to the mounted path just like a local file:# Replace with your actual data writing logic temperature = 25.5 # Example value from DHT11 with open('/mnt/remote_sensor_data/temp_log.txt', 'a') as f: f.write(f"{time.strftime('%Y-%m-%d %H:%M:%S')}, Temperature: {temperature}°C\n")
Pro Tip: To auto-mount the share on boot, add a line to
/etc/fstab(make sure to test the mount command first to avoid boot issues).
Solution 2: Use SSHFS (for Linux/macOS Targets)
If your remote PC runs Linux or macOS, SSHFS is a lightweight way to mount the remote directory over SSH.
Install SSHFS on your Pi:
sudo apt-get install sshfsCreate a mount point:
sudo mkdir /mnt/remote_ssh_dataMount the remote directory:
sshfs your_remote_user@192.168.1.100:/path/to/remote/folder /mnt/remote_ssh_dataFor passwordless access, set up SSH key pairs between your Pi and the remote PC (this is more secure than using passwords).
Write to the mounted path in your script:
Same as Solution 1—use the/mnt/remote_ssh_datapath withopen().
Solution 3: Direct Network File Transfer (No Mounting Required)
If you don't want to deal with mounting, use a Python library to send the data directly over the network. Here's an example using paramiko (for SSH/SFTP):
Install paramiko:
pip install paramikoAdd this function to your script:
import paramiko def write_via_sftp(data, remote_host, remote_user, remote_pass, remote_file_path): # Initialize SSH client ssh_client = paramiko.SSHClient() ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) try: # Connect to remote PC ssh_client.connect(remote_host, username=remote_user, password=remote_pass) # Open SFTP session sftp_session = ssh_client.open_sftp() # Write data to remote file with sftp_session.file(remote_file_path, 'a') as remote_file: remote_file.write(data) finally: # Clean up connections sftp_session.close() ssh_client.close()Call the function in your main logic:
def main(): # Your existing DHT11 reading code here # ... temperature = result.temperature # Assuming result is from dht11.read() log_entry = f"{time.strftime('%Y-%m-%d %H:%M:%S')}, Temperature: {temperature}°C\n" # Send data to remote PC write_via_sftp( data=log_entry, remote_host="192.168.1.100", remote_user="your_remote_username", remote_pass="your_remote_password", remote_file_path="/home/your_remote_username/sensor_logs/temp.txt" )
Common Troubleshooting Checks
- Network Connectivity: First, ping the remote PC's IP from your Pi (
ping 192.168.1.100) to confirm they're on the same network and can communicate. - Permissions: Ensure the remote folder has read/write permissions for your user account. On Linux, use
chmodorchownto adjust permissions if needed. - Firewall: Make sure the remote PC's firewall isn't blocking SMB/SSH connections (whitelist your Pi's IP if necessary).
内容的提问来源于stack exchange,提问作者OddDavis

