Skip to main content
 首页 » 编程设计

python之得到带有奇怪文本的输出,比如☻

2025年05月04日18傻小

嘿!我的脚本有问题。

看的时候写的LPTHW书。

我没有收到错误消息,但我没有得到正确的输出,我认为我的系统可能设置有误。我很困惑。

这是脚本:

from sys import argv 
 
script, filename = argv 
 
 
print "We're going to erase %r." % filename 
print "If you don't want that, hit CTRL-C (^C)." 
print "If you do want that, hit RETURN." 
 
raw_input("?") 
 
print "Opening the file..." 
target = open(filename, 'w+') 
 
print "Truncating the file. Goodbye!" 
target.truncate() 
 
print "Now I'm going to ask you for three lines." 
 
line1= raw_input("line1: ") 
line2= raw_input("line2: ") 
line3= raw_input("line3: ") 
 
print "I'm going to write these to the file." 
 
target.write(line1) 
target.write("\n") 
target.write(line2) 
target.write("\n") 
target.write(line3) 
target.write("\n") 
 
print "Now, I am going to read the file" 
print target.read() 
 
print "And finally, we close it." 
target.close() 

这是输出:

PS C:\Users\Isaac\lpthw> python ex1.py sample.txt 
We're going to erase 'sample.txt'. 
If you don't want that, hit CTRL-C (^C). 
If you do want that, hit RETURN. 
? 
Opening the file... 
Truncating the file. Goodbye! 
Now I'm going to ask you for three lines. 
line1: i 
line2: love 
line3: mo 
I'm going to write these to the file. 
Now, I am going to read the file 
#☻    ` ▬☻    ` ▬☻      .☻ 

请您参考如下方法:

当您调用target.write() 时,文件指针就留在写入的数据之后。你可以调用 target.tell() 来查看它在哪里:

>>> target.tell() 
0 
>>> target.write('hello') 
>>> target.tell() 
5 

在读取文件之前需要查找到文件的开头:

target.seek(0) 
print target.read()