如何在运行时更改目录并将文件存储在其他位置

时间:2019-07-10 07:34:03

标签: python file directory filepath file-handling

假设我正在将学生详细信息作为列表写入CSV文件。 目前,我正在以下目录中工作:

    BluetoothManager btManager; //field 'btManager' is never used
    private BluetoothAdapter btAdapter = null;
    BluetoothLeScanner btScanner;
    Button startScanningButton;
    Button stopScanningButton;
    TextView peripheralTextView;
    private final static int REQUEST_ENABLE_BT = 1;
    private static final int PERMISSION_REQUEST_COARSE_LOCATION = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        peripheralTextView = (TextView) findViewById(R.id.peripheralTextView);
        peripheralTextView.setMovementMethod(new ScrollingMovementMethod());

        startScanningButton = (Button) findViewById(R.id.StartScanButton);
        startScanningButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                startScanning();
            }
        });

        stopScanningButton = (Button) findViewById(R.id.StopScanButton);
        stopScanningButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                stopScanning();
            }
        });
        stopScanningButton.setVisibility(View.INVISIBLE);

        final BluetoothManager btManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        btAdapter = btManager.getAdapter();
        btScanner = btAdapter.getBluetoothLeScanner();

        if (btAdapter != null && !btAdapter.isEnabled()) {
            Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableIntent,REQUEST_ENABLE_BT);
        }

        // Make sure we have access coarse location enabled, if not, prompt the user to enable it
        if (this.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            final AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("This app needs location access");
            builder.setMessage("Please grant location access so this app can detect peripherals.");
            builder.setPositiveButton(android.R.string.ok, null);
            builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialog) {
                    requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, PERMISSION_REQUEST_COARSE_LOCATION);
                }
            });
            builder.show();
        }
    }

    // Device scan callback.
    private ScanCallback leScanCallback = new ScanCallback() {
        @Override
        public void onScanResult(int callbackType, ScanResult result) {
            peripheralTextView.append("MAC address: " + result.getDevice().getAddress() + " rssi: " + result.getRssi() + "TxPower:" + result.getTxPower() + "\n");

            // auto scroll for text view
            final int scrollAmount = peripheralTextView.getLayout().getLineTop(peripheralTextView.getLineCount()) - peripheralTextView.getHeight();
            // if there is no need to scroll, scrollAmount will be <=0
            if (scrollAmount > 0)
                peripheralTextView.scrollTo(0, scrollAmount);
        }
    };

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String permissions[], int[] grantResults) {
        switch (requestCode) {
            case PERMISSION_REQUEST_COARSE_LOCATION: {
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    System.out.println("coarse location permission granted");
                } else {
                    final AlertDialog.Builder builder = new AlertDialog.Builder(this);
                    builder.setTitle("Functionality limited");
                    builder.setMessage("Since location access has not been granted, this app will not be able to discover beacons when in the background.");
                    builder.setPositiveButton(android.R.string.ok, null);
                    builder.setOnDismissListener(new DialogInterface.OnDismissListener() {

                        @Override
                        public void onDismiss(DialogInterface dialog) {
                        }

                    });
                    builder.show();
                }
            }
        }
    }

    public void startScanning() {
        System.out.println("start scanning");
        peripheralTextView.setText("");
        startScanningButton.setVisibility(View.INVISIBLE);
        stopScanningButton.setVisibility(View.VISIBLE);
        AsyncTask.execute(new Runnable() {
            @Override
            public void run() {
                btScanner.startScan(leScanCallback);
            }
        });
    }

    public void stopScanning() {
        System.out.println("stopping scanning");
        peripheralTextView.append("Stopped Scanning");
        startScanningButton.setVisibility(View.VISIBLE);
        stopScanningButton.setVisibility(View.INVISIBLE);
        AsyncTask.execute(new Runnable() {
            @Override
            public void run() {
                btScanner.stopScan(leScanCallback);
            }
        });
    }
}

但是我想将这些CSV文件存储在/home/ubuntu/Desktop/Pythontraining 文件夹中,该文件夹位于:

"StudentDetails"

以及

/home/ubuntu/Desktop/StudentDetails 

我想在运行时将CSV文件存储在两个目录中。我正在创建一个新文件(输出文件),但是我想将其存储在另一个目录中。说,我需要将“输出文件”存储到名称为“ StudentDetails”的文件夹中。就我而言,我已经在两个不同的目录中创建了“ StudentDetails”文件夹。

我想将文件(输出文件)保存在两个目录中。我应该如何手动进行?

/home/ubuntu/Documents/StudentDetails

1 个答案:

答案 0 :(得分:0)

据我了解,您需要将同一文件保存在两个不同的目录中,并以方便的方式进行。 至少有两种方法:

  1. 您可以创建一个函数,该函数会将所需的数据循环保存到两个不同的文件中。并且我们需要一个函数来使我们的代码可读:

    def multiple_save_st_details(m, path1, path2):
        for outfile in [path1, path2]:
            try:
                f=open(outfile, 'w')
                for j in m:
                    writer = csv.writer(f)
                    writer.writerow(j)
            except OSError as o:
                print("Can't Change the current directory")
    
  2. 我们有一个文件到第一个位置,然后将其复制到另一个目录:

    def save_w_copy_st_details(m, filepath1, path2):
        try:
            f=open(filepath1, 'w')
            for j in m:
                writer = csv.writer(f)
                writer.writerow(j)
        except OSError as o:
            print("Can't Change the current directory")
        import shutil
        shutil.copy2(filepath1, path2)
    

在这种情况下,目标路径的文件名可能会被排除,并与源文件中的文件名相同