Python 同步电脑上的文件夹路径
Python folder paths on synched pcs
我在两台不同的电脑上使用 .py 文件并使用 google 驱动器同步文件。
由于我经常使用子文件夹处理文件,因此我使用完整路径来读取 csv
passport = pd.read_csv(r'C:\Users\turbo\Google Drive\Studium\Master_thesis\Python\Databases\passport_uzb.csv')
但是,切换电脑时我必须手动更改路径,因为我的第二台电脑是:
C:\Users\turbo\My Drive\Studium\Master_thesis\Python\Databases
所以唯一的区别是 'Google Drive' =/= 'My Drive'
是否可以使用完整的文件路径来读取文件?
您可以使用 relative 路径而不是 absolute 路径来访问 CSV。 pathlib
module is useful for this. For example, assuming your script is directly inside the ...Python/Databases
folder, you can compute the path to the CSV like so, using the __file__
模块属性:
from pathlib import Path
# this is a path object that always refers to the script in which it is defined
this_file = Path(__file__).resolve()
# this path refers to .../Python/Databases, no matter where it is located
this_folder = this_file.parent
csv_path = this_folder / "passport_uzb.csv"
passport = pd.read_csv(csv_path)
Edit:无论您的脚本位于何处,您都可以使用 .parent
和 / "child"
的某种组合来构造一个有效的相对路径.如果您的脚本在 ...Python/Databases/nasapower
中,则只需添加另一个 .parent
:
this_file = Path(__file__).resolve()
nasapower_folder = this_file.parent
databases_folder = nasapower_folder.parent
或者您可以使用 .parents
序列来更快地到达那里:
databases_folder = Path(__file__).resolve().parents[1]
同样,对于输出文件夹:
output_folder = Path(__file__).resolve().parent / "json"
我在两台不同的电脑上使用 .py 文件并使用 google 驱动器同步文件。 由于我经常使用子文件夹处理文件,因此我使用完整路径来读取 csv
passport = pd.read_csv(r'C:\Users\turbo\Google Drive\Studium\Master_thesis\Python\Databases\passport_uzb.csv')
但是,切换电脑时我必须手动更改路径,因为我的第二台电脑是:
C:\Users\turbo\My Drive\Studium\Master_thesis\Python\Databases
所以唯一的区别是 'Google Drive' =/= 'My Drive'
是否可以使用完整的文件路径来读取文件?
您可以使用 relative 路径而不是 absolute 路径来访问 CSV。 pathlib
module is useful for this. For example, assuming your script is directly inside the ...Python/Databases
folder, you can compute the path to the CSV like so, using the __file__
模块属性:
from pathlib import Path
# this is a path object that always refers to the script in which it is defined
this_file = Path(__file__).resolve()
# this path refers to .../Python/Databases, no matter where it is located
this_folder = this_file.parent
csv_path = this_folder / "passport_uzb.csv"
passport = pd.read_csv(csv_path)
Edit:无论您的脚本位于何处,您都可以使用 .parent
和 / "child"
的某种组合来构造一个有效的相对路径.如果您的脚本在 ...Python/Databases/nasapower
中,则只需添加另一个 .parent
:
this_file = Path(__file__).resolve()
nasapower_folder = this_file.parent
databases_folder = nasapower_folder.parent
或者您可以使用 .parents
序列来更快地到达那里:
databases_folder = Path(__file__).resolve().parents[1]
同样,对于输出文件夹:
output_folder = Path(__file__).resolve().parent / "json"