You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python将文件写入并保存到同网络另一机器?DHT11脚本存文件失败求助

How to Write Sensor Data to a Remote PC on the Same Network with Python

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.

  1. 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.conf with write permissions.
  2. Prepare your Raspberry Pi:
    Install the tools to mount SMB shares:

    sudo apt-get update && sudo apt-get install cifs-utils
    
  3. Create a local mount point:

    sudo mkdir /mnt/remote_sensor_data
    
  4. Mount 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=YourSambaPass
    
  5. Update 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.

  1. Install SSHFS on your Pi:

    sudo apt-get install sshfs
    
  2. Create a mount point:

    sudo mkdir /mnt/remote_ssh_data
    
  3. Mount the remote directory:

    sshfs your_remote_user@192.168.1.100:/path/to/remote/folder /mnt/remote_ssh_data
    

    For passwordless access, set up SSH key pairs between your Pi and the remote PC (this is more secure than using passwords).

  4. Write to the mounted path in your script:
    Same as Solution 1—use the /mnt/remote_ssh_data path with open().

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):

  1. Install paramiko:

    pip install paramiko
    
  2. Add 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()
    
  3. 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 chmod or chown to 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:03:21