首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >将文本文件中的值赋给可用于python中下一步的变量

将文本文件中的值赋给可用于python中下一步的变量
EN

Stack Overflow用户
提问于 2018-07-02 16:30:07
回答 1查看 88关注 0票数 0

我对python脚本非常陌生。我想创建一个可以打开文本文件c_name.txt的脚本,其中文本文件的内容是单元格名称列表。打开后,我需要将所有单元格名称指定为一个变量。这是因为我需要单元名称来打开下一个需要单元名称的目录。我现在所做的就是打开文本文件并打印单元格名称。我不知道如何读取单元格名称并将其赋值给变量。是否需要将所有单元格名称分配到一个数组中?

我还需要对单元格名称以ce_开头的情况进行分类,如果单元格名称以ce_开头,则报告文件将位于单元目录中。

这是我的c_name.txt:

代码语言:javascript
复制
ce_clk
celladd
ce_sum
cellsub

以下是更新后的代码:

代码语言:javascript
复制
#!/usr/bin/python

import os
import os.path

myPWD = os.getcwd()

# Implement functions get_test_directory and get_library_directory
# to retrieve correct directory paths
def get_test_directory( str ):
    return str

def get_library_directory (str ):
    os.chdir('..')
    str = os.getcwd()
    return str

test_directory = get_test_directory(myPWD)
library_directory = get_library_directory(myPWD)

cell_names_file = os.path.join(test_directory, "c_name.txt")

with open(cell_names_file, "r+") as f1:
    cell_names = f1.readlines()

for cell_name in cell_names:
    cell_directory = "ce_" if cell_name.startswith("ce_") else "cell"
    floc2 = os.path.join(library_directory, cell_directory, "{0}.rpt".format(cell_name))
    with open(floc2, "r+") as f2:
        for line in f2:
                 print line

新的编辑:我有另一个关于行开始的问题,使它更通用,而不是使用硬编码,如下所示:

代码语言:javascript
复制
for cell_name in cell_names:
        cell_directory = "ce_" if cell_name.startswith("ce_") else "cell"
        floc2 = os.path.join(library_directory, cell_directory,{0}.rpt".format(cell_name))

现在我使用"ce_“和"cell",是否可以让脚本读取cell_name的前3个字符,即"ce_”和"cel“而不是自己定义它。我尝试使用这一行,但它似乎不起作用,因为它显示错误:

代码语言:javascript
复制
cell_directory = cell_name.startswith(cell_name,0,5)

错误:

代码语言:javascript
复制
AttributeError: 'bool' object has no attribute 'startswith'
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-07-02 16:38:26

在您当前的示例中,将值存储到列表中就足够了。稍后,当您需要这些值时,遍历列表并逐个获取每个单元格的名称。

代码语言:javascript
复制
#!/usr/bin/python

import os
import os.path

myPWD = os.getcwd()

# Implement functions get_test_directory and get_library_directory
# to retrieve correct directory paths
test_directory = get_test_directory(myPWD)
library_directory = get_library_directory(myPWD)

cell_names_file = os.path.join(test_directory, "c_name.txt")

with open(cell_names_file, "r+") as f1:
    cell_names = [line.strip() for line in f1]

for cell_name in cell_names:
    cell_directory = "ce_" if cell_name.startswith("ce_") else "cell"
    floc2 = os.path.join(library_directory, cell_directory, "{0}.rpt".format(cell_name))

编辑:代码已更新,以说明问题中的新信息。没有关于目录结构的精确信息,所以我使用虚拟占位符。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51131937

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档