【发布时间】:2018-02-23 23:16:33
【问题描述】:
我需要从 txt 文件中读取颜色列表。例如 color.txt 看起来像这样:
red
blue
green
我做的是:
with open('color.txt') as f:
line = f.readline().strip()
当调用 'line' 时,我的结果是:
'red'
'blue'
'green'
但是,我需要没有''的输出:
red
blue
green
是我的txt文件编码有问题吗?还是我做错了什么? 提前感谢您的帮助。
更新: 由于对我在这里所做的工作没有明确的了解,请查看完整代码。该程序应在定义的列数中打印彩色矩形。矩形的数量由文件中的颜色数量定义。每个矩形都有一行一行的颜色。
import tkinter
canvas = tkinter.Canvas()
canvas.pack()
def stvor(file, width):
a = 30
pocetr = 0
z = 0
with open(file, 'r') as f:
x = 10
y = 10
for line in f: #line counter
pocetr += 1
for b in range(pocetr): #defined how many rectangles shall be drawn
z += 1
col = f.readline().strip() #reading color from a file
canvas.create_rectangle(x, y, x+a, y+a, fill = col)
x = x + a
if z == width: #if the width reaches certain level continue in new line
y = y + a
x = 10
z = 0
【问题讨论】:
-
只是字符串表示,打印字符串时使用。
-
@heemayl 文件中的一行会以
\n结尾。 -
@JoshLee 他可能正在用未显示的代码对其进行修剪。
-
您的输出不可能由您的代码生成。你能告诉我们真实的输出以及它是如何产生的吗?特别是,您所说的“调用'line'”是什么意思?你的代码有循环吗?
-
你说得对,我会得到'red\n'。但是这个我可以很容易地用 strip() 删除。
标签: python python-3.x text readline apostrophe