python - 打印字符串,而不是字符数

标签 python python-3.x

我正在努力工作,因为我是一名全新的编码员。好吧,我还没有学到那么多,所以我正在做基本的代码。 我使用随机变量来打印变量附带的字符串,而不是字符串中的字符数。

抱歉,如果有人生气,但我似乎无法在任何地方找到此问题的解决方案,如果有的话,我一定输入了错误的搜索

提前谢谢您。

代码:

import random

EFile=open("ExternalFile.txt","w+")
Info1=EFile.write("Shotgun - George Ezra")
Info2=EFile.write("God's Plan - Drake")
Info3=EFile.write("This is me - Kiara Settle")
Info4=EFile.write("Solo - Clean Bandit")
Info5=EFile.write("Psyco - Post Malone")
EFile.close

Array=[Info1, Info2, Info3, Info4, Info5]


Efile=open("ExternalFile.txt","r")

RanVar=random.choice(Array)
print(RanVar)

我希望它打印括号中的字符串,但它打印字符数,我不明白为什么。

最佳答案

EFile.write(string)的返回值是写入的字符数,而不是写入的内容。最好将要写入文件的所有内容存储在列表中。我还假设您想用换行符写每首歌曲的名称。另外,这不是强制性的,但变量名不需要大写,也不符合约定。

import random

songs = ["Shotgun - George Ezra", "God's Plan - Drake", "This is me - Kiara Settle", "Solo - Clean Bandit", "Psyco - Post Malone"]

efile = open("ExternalFile.txt", "w+")

for song in songs:
    efile.write(song + "\n")

efile.close()

ran_var = random.choice(songs)
print(ran_var)

对于您的技能水平来说,这可能有点高级,但是使用 with block 来处理文件是很好的选择:

with open("ExternalFile.txt", "w+") as efile:
    for song in songs:
        efile.write(song + "\n")

with block 自动关闭文件。

关于python - 打印字符串,而不是字符数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54070986/

相关文章:

python - 从 Python 数据类装饰器中的 __repr__ 方法中删除引号

javascript - Flask Ajax 执行前返回多个状态

Django 信号重定向

python - 我怎样才能为 gconf 制作一个假的 "active session"?

python - 是否可以训练 AI 仅使用一张图像对图像进行分类?

python-3.x - 使用 Python 3.6 使用个人访问 token 对 VisualStudioOnline REST API 进行身份验证

python - 从订阅者调用远程过程并解决 asyncio promise

python - 简单的链表队列

python - Python 中程序实例的队列?

Python 跨子类共享日志记录