用Python编写一个.txt文件,类名从0到N不等

2024-10-05 14:26:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个名为myClass的类,它包含一些属性(attribute0,attibute1…)。你知道吗

我已经创建了N个myClass(myClass0,myClass1…)。你知道吗

要写入.txt文件myClass0.attribute0:

fichier = open("myFile.txt", "a")
fichier.write("{}".format(myClass0.attribute0))

我想写在文件里myFile.txt文件我的分类属性0N表示0到9:

fichier = open("myFile.txt", "a")
fichier.write("{}".format(myClass0.attribute0))
fichier.write("{}".format(myClass1.attribute0))
.
.
.
fichier.write("{}".format(myClass9.attribute0))

如何循环进行?你知道吗


Tags: 文件txtformat属性myclass分类openmyfile
1条回答
网友
1楼 · 发布于 2024-10-05 14:26:48

仅循环代码-请用以下内容替换.write行:

class_list = [myClass0, myClass1, myClass2 ,etc.]
for instance in class_list:
    myFile.append("{}".format(instance.attribute0))

另外要澄清的是,如果您试图将所有类名都放在一个文件中,则不能使用.write file方法,因为它会覆盖文件中已有的任何内容—这就是为什么在添加到现有文件时使用.append的原因。你知道吗

*作为旁注,通常首选使用

with open(file_name) as my_file: # do stuff here

而不是将打开的文件附加到变量。你知道吗

使用下划线来分隔变量名中的单词也是公认的做法,而不是Python中的驼峰大小写(wordWord),如PEP8所示:

函数名应该是小写的,单词之间用下划线隔开以提高可读性。变量名遵循与函数名相同的约定。“*

相关问题 更多 >