1

所以,我有一个文本文件,内容如下:

###############
###############
###############
###############
###############
###############
###############
###############
###############
###############
###############
###############
###############
###############

我编写了一些代码,应该将跟踪器(就是它的名字吗?)移动到您指定的坐标:

f = open('graphs.txt', 'r+')

while True:
    # TODO: Make an error if X or Y is greater than 15.
    x = input('X = ')
    y = input('Y = ')

    # this thing here finds which character to replace, 
    s = x + y * 16 # this is how far the tracker seeks
    f.seek(s)

不幸的是,我不知道如何操作跟踪器所在的单个角色。我所知道的有关读取和写入文件的所有操作基本上都涉及更改整个文件。有没有办法用“*”替换一个指定的“#”?

编辑:我想通了,但现在我有一个新问题。

4

3 回答 3

2

您可以找到该位置,然后使用readwrite命令更改文件。

但是请注意,文本文件对此很烦人,您应该使用二进制文件。

下面是一个程序,它创建一个包含 256+16 个'#'字符(16 + '\n' x 16)的文件(如果文件不存在),而是“绘制”一条带星号的线,'*'x0,y0x1y1如果文件存在)。

try:
    f = open("draw.txt", "rb+")
except IOError:
    print "File was not present: creating it"
    f = open("draw.txt", "wb+")
    f.write(("#"*16 + "\n") * 16)

请注意,文件以二进制模式打开以避免随机查找/写入问题

# Ask coordinates
x0 = int(raw_input("x0: "))
y0 = int(raw_input("y0: "))
x1 = int(raw_input("x1: "))
y1 = int(raw_input("y1: "))

# Line drawing DDA algorithm
dx = abs(x1 - x0)
ix = 1 if x0 < x1 else -1
dy = abs(y1 - y0)
iy = 1 if y0 < y1 else -1
m = max(dx, dy)
cx = cy = m >> 1

以上是需要计算线斜率和要绘制的像素数,以下是实际的 DDA 循环:

for i in xrange(m + 1):
    if 0 <= x0 < 16 and 0 <= y0 < 16:
        # Valid pixel; draw
        f.seek(y0*17 + x0)
        f.write('*')
    # Move to next pixel
    cx += dx
    if cx >= m:
        cx -= m
        x0 += ix
    cy += dy
    if cy >= m:
        cy -= m
        y0 += iy

请注意,代码将查找位置计算为y*(16+1)+x:额外1用于每行上存在的换行符。最后关闭文件。

# All done
f.close()

以下是程序运行两次后的文件内容:

################
################
###########*####
###*######*#####
####**####*#####
######**#*######
########**######
########*#**####
#######*########
######*#########
######*#########
#####*##########
################
################
################
################

上面的代码处理 Linux 或其他类 unix 系统的文件。如果 Windows 操作系统需要文本文件,您将不得不使用序列\r\n作为行终止符(因此每行两个额外的字符),而不仅仅是\n. 如果相反是 Mac,您将需要\r而不是\n.

不能保证以文本模式打开文件,因为(至少在形式上)您只能ftell在线性扫描期间读取的位置寻找,并且不允许在文件中间写入。

于 2013-11-03T13:46:12.003 回答
0

因此,事实证明 write() 使用覆盖而不是插入,这使事情变得更有帮助。这段代码正是我想要它做的,减去了 read() 位,由于我不明白的原因,它被破坏了。

f = open('graph.txt', 'rb+')

while True:
    # TODO: Make an error if X or Y is greater than 15.
    x = input('X = ')
    y = input('Y = ')

    # this thing here finds which character to replace, 
    s = x + (y * 16) # this is how far the tracker seeks
    f.seek(s)
    f.write('*')

    f.seek(0, 0)
    print f.read()
于 2013-11-03T14:58:36.463 回答
-2

将整个文件作为字符串读取。然后,替换您想要的任何字符和该等式的索引。

stringthing = file.read //or whatever the read command is
stringthing[s] = '[whatever your char is]'
[write stringthing to file]

有帮助吗?

于 2013-11-03T13:30:09.300 回答