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

Python包跨模块调用相对路径函数及PyPI上传文件问题

Great question! Let's break this down into two clear parts: fixing the file path loading issue first, then walking through how to package your project and upload it to PyPI.

Part 1: Fixing Relative Path Loading Across Modules

The root problem here is that Python uses your current working directory (CWD) as the base for relative paths. When you run utils.py directly, your CWD is pkg/, so files/1.txt works. But when you run main.py from the project root, your CWD is the root folder, so Python looks for root/files/1.txt which doesn't exist.

To fix this without modifying your original relative path structure, we need to anchor the path to the actual location of utils.py (the package directory) instead of relying on the CWD. Here are two clean ways to do it:

Using os.path (compatible with all Python 3 versions)

Update your utils.py like this:

import os

# Get the absolute path of the directory containing utils.py
PACKAGE_ROOT = os.path.dirname(os.path.abspath(__file__))

def load_1txt():
    # Use the package root as the base for your relative path
    file_path = os.path.join(PACKAGE_ROOT, "files/1.txt")
    with open(file_path, "r") as f:
        return f.read()

Using pathlib (Python 3.4+, more modern)

If you're on a newer Python version, pathlib makes this even cleaner:

from pathlib import Path

# __file__ points to utils.py; .parent gives us the pkg/ directory
PACKAGE_ROOT = Path(__file__).parent

def load_1txt():
    # Path objects support intuitive path joining with /
    file_path = PACKAGE_ROOT / "files" / "1.txt"
    return file_path.read_text()

Now no matter where you call this function from (main.py or elsewhere), it will always look for pkg/files/1.txt correctly.

Part 2: Packaging Your Project & Uploading to PyPI

To turn this into a distributable Python package, follow these steps:

1. Refine Your Project Structure

First, adjust your directory to match the standard Python package layout (this makes packaging much smoother):

your-package-name/  # Root folder (name this whatever you want for PyPI)
|-- main.py
|-- pkg/
|   |-- __init__.py  # REQUIRED: Empty file to mark this as a Python package
|   |-- utils.py
|   |-- files/
|       |-- 1.txt
|       |-- 2.txt
|-- pyproject.toml  # Core packaging config file
|-- README.md  # Optional but recommended: Explain your package's purpose

The __init__.py file is mandatory—without it, Python won't recognize pkg as an importable package.

2. Write the pyproject.toml Config

This file tells Python how to build your package. Here's a complete example tailored to your project:

[build-system]
requires = ["setuptools>=61.0"]
build-backend = "setuptools.build_meta"

[project]
name = "your-package-name"  # Must be unique on PyPI
version = "0.1.0"
authors = [
  { name="Your Full Name", email="your.email@example.com" }
]
description = "A short, clear description of what your package does"
readme = "README.md"
requires-python = ">=3.7"
classifiers = [
  "Programming Language :: Python :: 3",
  "License :: OSI Approved :: MIT License",  # Pick a license that fits
  "Operating System :: OS Independent",
]

# Critical: Tell setuptools to include your text files in the package
[tool.setuptools.package-data]
pkg = ["files/*.txt"]

The package-data section ensures that your files/ directory and its contents are included in the final package—this is essential so users who install your package can load those text files properly.

3. Build the Package

First install the build tool:

pip install build

Then run this command from your project root (the your-package-name/ folder):

python -m build

This will create a dist/ folder with two files: a source tarball (.tar.gz) and a wheel file (.whl)—these are the distributable packages you'll upload to PyPI.

4. Upload to PyPI

First, you'll need an account on PyPI. Then install the upload tool:

pip install twine

Finally, upload your built packages:

twine upload dist/*

Follow the prompts to enter your PyPI username and password. Once uploaded, anyone can install your package with:

pip install your-package-name

Pro Tip: Test First on TestPyPI

If you want to test the packaging and upload process without cluttering the main PyPI, use TestPyPI instead:

twine upload --repository testpypi dist/*

To install the test version:

pip install --index-url https://test.pypi.org/simple/ your-package-name

内容的提问来源于stack exchange,提问作者imhuay

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 04:21:09