Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/cassandra/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
我想使用python从文件中获取一个变量_Python - Fatal编程技术网

我想使用python从文件中获取一个变量

我想使用python从文件中获取一个变量,python,Python,我有一个包含以下内容的文本文件: List : 1 2 3, 5 6 7 N:7 我想取N的值,它是7: 我的代码: def imp_res(): # Get the content of the named resource as a string. data = resources.GetResource( 'experimental/users/abhijitsahani/file/input.txt', mode='rt')

我有一个包含以下内容的文本文件:

 List : 1 2 3, 5 6 7
 N:7
我想取N的值,它是7:

我的代码:

 def imp_res():
    # Get the content of the named resource as a string.
    data = resources.GetResource(
       'experimental/users/abhijitsahani/file/input.txt', 
         mode='rt')

    for line in data:
       if 'N' in line:
          val = line.split(':')[-1].strip()
    print('Content :', val)
电流输出:

  content : N
预期产出:

  Content : 7

如果
data
是一个字符串(如代码注释所示)而不是一个文件(如标题所示),那么您只需迭代字符串的每个字符,最后将
N
赋值给val

有两种解决方案

  • 将任何
    resources.GetResource
    更改为简单的
    open
  • 数据
    包装在
    io.StringIO中
  • e、 g

    将打印

    Content : 7
    
    我希望您的代码所做的是在对数据进行迭代之前,对数据进行
    read()
    调用。取消对该行的注释,您将获得

    Content : N
    

    你的代码对我有用。你确定这就是你正在运行的吗?@Avi319170,我同意tomjn的观点,它对我很有用。是的。我越来越N@Avi319170您的数据是文件对象还是字符串?这可能意味着您的数据不是您/我们所想的。我会仔细看一下文件。
    Content : N