【问题标题】:Difference between Linux and Windows in Python addressing CSV filesLinux 和 Windows 在 Python 寻址 CSV 文件中的区别
【发布时间】:2018-07-10 16:49:36
【问题描述】:

我正在尝试从 Windows 迁移到 Linux,我的一些 Python 代码没有在迁移中幸存下来。

这是 Windows 版本:

path = r'C:\\Users\\x\\PythonTestFiles\\TestFile.csv'
file = open(path, newline='')
TestFileRaw = csv.reader(file)

header = next(TestFileRaw)
dataPC = [row for row in TestFileRaw]

等等……

我正在尝试对某个目录中的 csv 文件进行寻址,但我无法确定 Linux 寻址。

谁能帮忙?

【问题讨论】:

  • 为什么不提供文件路径作为命令行参数?

标签: python linux csv addressing


【解决方案1】:

这里有一些关于 linux 的信息 directory structure

在您的文件上按 Alt + Enter,然后在该属性对话框中将路径复制到根目录,例如 /home/<user_name>/Documents,然后将该路径附加到 csv 文件的 file name

在最终你的 csv 文件的路径变成了类似

/home/<user_name>/Documents/filename.csv

【讨论】:

    【解决方案2】:

    您可以使用os 模块中的分隔符:

    import os
    path = os.path.join('your_folder_name', 'your_file_name')
    

    这样它就可以独立于 Windows/Linux。

    这里是official documentation to os.path module

    【讨论】:

    • 在 Windows 上是的。你也可以使用os.sep 来构建你的路径:在Linux 上os.sep = '/'。我添加了文档链接来回答。
    【解决方案3】:

    在 linux 中使用你的 csv 文件的任何路径!

    path = r'/home/x/python_test_files/test_file.csv'
    file = open(path, newline='')
    TestFileRaw = csv.reader(file)
    
    header = next(TestFileRaw)
    dataPC = [row for row in TestFileRaw]
    

    【讨论】:

      猜你喜欢
      • 2014-10-27
      • 2011-02-13
      • 2019-02-27
      • 2015-05-09
      • 1970-01-01
      • 1970-01-01
      • 2015-01-20
      • 2020-12-01
      • 2020-07-22
      相关资源
      最近更新 更多