pandas 如何将文件路径变量放入pandas.read_csv?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35466247/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 00:43:04  来源:igfitidea点击:

How do I put a file path variable into pandas.read_csv?

pythoncsvpandasoperating-systemenviron

提问by johntan05

I tried to apply it through os.environ like so:

我试图通过 os.environ 像这样应用它:

import os
import pandas as pd

os.environ["FILE"] = "File001"

df = pd.read_csv('/path/$FILErawdata.csv/')

But pandas doesn't recognize $FILEand instead gives me $FILErawdata.csv not found

但Pandas不承认$FILE,而是给我$FILErawdata.csv not found

Is there an alternative way to do this?

有没有其他方法可以做到这一点?

回答by Bryant Kou

New Answer:

新答案:

If you like string interpolation, python now uses f-strings for string interpolation:

如果你喜欢字符串插值,python 现在使用f-strings 进行字符串插值

import os
import pandas as pd

filename = "File001"

df = pd.read_csv(f'/path/{filename}rawdata.csv/')

Old Answer:

旧答案:

Python doesn't use variables like shells scripts do. Variables don't get automatically inserted into strings.

Python 不像 shell 脚本那样使用变量。变量不会自动插入到字符串中。

To do this, you have to create a string with the variable inside.

为此,您必须创建一个包含变量的字符串。

Try this:

尝试这个:

import os
import pandas as pd

filename = "File001"

df = pd.read_csv('/path/' + filename + 'rawdata.csv/')

回答by Happy001

df = pd.read_csv('/path/%(FILE)srawdata.csv' % os.environ)

I suspect you need to remove the trailing '/'.

我怀疑您需要删除尾随的“/”。