Python:VB 程序员的基本命名元组集合

Python: Basic Namedtuple Collections for VB Programmers

我正在 Python 上开发我的第一个“Hello World”!很久很久以前,我曾经是 Visual Basic 程序员...

我正在尝试使用如下的 Namedtuple 集合:

#!/usr/bin/env python3
    
import collections
    
#Tipo da colecao
File = collections.namedtuple('File',['abspath' ,'basename','filextention','filetype'])
Files = []
    
Files.append(File('/home/user/teste1.txt', 'teste1.txt','txt',''))
Files.append(File('/home/user/teste2.txt', 'teste2.txt','txt',''))
Files.append(File('/home/user/teste3.txt', 'teste2.txt','txt',''))
    
for lCtd in range(0,len(Files)):
    print(Files[lCtd].abspath,Files[lCtd].basename,Files[lCtd].filextention)
    
for lCtd in range(0,len(Files)):
    #>>>>>How can I do this?!<<<<< 
    Files[lCtd].filetype = 'A' 

如果有最好的方法(或所有代码),我洗耳恭听...

非常感谢!

命名元组很有用,但它们不可变:它们的属性在创建后无法更改。如果你想要一个同样方便的可变数据持有者,你可能会对 data classes 感兴趣,只要你使用 Python 3.7 或更新版本。

from dataclasses import dataclass

@dataclass
class File:
    file_name: str
    abs_path: str
    base_name: str
    file_extension: str
    # The '=' below sets a default value. (You could use '', but None is more
    # commonly used for this.)
    file_type: str =  None

files = [
    File('/home/user/test1.txt', 'test1.txt', 'txt'),
    File('/home/user/test2.txt', 'test2.txt', 'txt'),
    File('/home/user/test3.txt', 'test3.txt', 'txt'),
]
    
for file in files:
    print(file.abs_path, file.base_name, file.file_extension)
    # This will update the file_type attribute for each file:
    file.file_type = 'A'

请注意,更 Pythonic 遍历列表(或任何序列)的方法是不依赖 len 和索引,而只是循环遍历项目本身。

综上所述,如果您正在寻找一种处理文件的简单方法,例如获取文件的名称和扩展名,您可能还应该看看 Pathlib

from pathlib import Path

file = Path('/home/user/test1.txt')
print(str(file), file.name, file.suffix)

# Output: /home/user/test1.txt test1.txt .txt

P.S。 file 是 Python 2 中的一个内置项,许多编辑可能仍会这样突出显示它,但在 Python 3 中用作 variable/class 名称应该没问题。

看来你真正想要的是定义你自己的class,像这样:

class File:
    # make a constructor, with a default parameter (for convenience!)
    def __init__(self, abspath, basename, filextention, filetype = ''):
        self.abspath = abspath
        self.basename = basename
        self.filextention = filextention
        self.filetype = filetype

Files = []

# this part is almost the same, but you don't need the last parameter
# because we gave it a default value    
Files.append(File('/home/user/teste1.txt', 'teste1.txt','txt'))
Files.append(File('/home/user/teste2.txt', 'teste2.txt','txt'))
Files.append(File('/home/user/teste3.txt', 'teste2.txt','txt'))

# this is a better way to loop over a list in Python:
for curFile in Files:
    print(curFile.abspath, curFile.basename, curFile.filextention)

for curFile in Files:
    curFile.filextention = 'A' # in Python all fields are public by default and can be assigned like this