Python 从文本文件中删除额外空间

Python 从文本文件中删除额外空间,python,whitespace,Python,Whitespace,我目前将高分保存在一个名为“score.txt”的文本文件中。prgoram可以正常工作,用新的高分更新文件。除了每次程序更新文件时,在第一个高分之前总是有一个空行,这会在我下次尝试保存分数时产生错误。守则: scores_list = [] score = 10 def take_score(): # Save old scores into list f = open("score.txt", "r") lines = f.readlines() for

我目前将高分保存在一个名为“score.txt”的文本文件中。prgoram可以正常工作,用新的高分更新文件。除了每次程序更新文件时,在第一个高分之前总是有一个空行,这会在我下次尝试保存分数时产生错误。守则:

scores_list = []
score = 10


def take_score():
     # Save old scores into list
    f = open("score.txt", "r")
    lines = f.readlines()
    for line in lines:
        scores_list.append(line)
    print scores_list
    f.close()

take_score()


def save_score():
    # Clear file
    f = open("score.txt", "w")
    print >> f, ""
    f.close()
    # Rewrite scores into text files
    w = open("score.txt", "a")
    for i in range(0, len(scores_list)):
        new_string = scores_list[i].replace("\n", "")
        scores_list[i] = int(new_string)
        if score > scores_list[i]:
            scores_list[i] = score
    for p in range(0, len(scores_list)):
        print >> w, str(scores_list[p])
        print repr(str(scores_list[p]))

save_score()

上述问题发生在
save_score()
函数中。我尝试过这个相关的问题:,但它要求我以
“r”
模式打开文件。除了在
“a”
模式(append)下打开文件外,是否有其他方法可以完成相同的操作?

打印
在打印内容后追加一行换行符。排队

print >> f, ""
您正在向文件中写入换行符。在追加模式下重新打开时,此换行符仍然存在


正如@Zizouz212提到的,你不需要做所有这些。只需在写入模式下打开,该模式将截断文件,然后写入您需要的内容。

创建文件后,您将特别打印一行空行

print >> f, ""
然后附加到它,保留空行

如果您只想在每次运行此操作时清除内容,请删除以下内容:

# Clear file
f = open("score.txt", "w")
print >> f, ""
f.close()
并将洞口修改为:

w = open("score.txt", "w")
'w'
模式已经截断,因为您已经在使用。不需要截断、写空行、关闭然后追加行。只需截断并写出你想写的东西

也就是说,您应该使用
with
构造和文件方法来处理文件:

with open("score.txt", "w") as output: # here's the with construct
    for i in xrange(len(scores_list)):
        # int() can handle leading/trailing whitespace
        scores_list[i] = int(scores_list[i])
        if score > scores_list[i]:
            scores_list[i] = score
    for p in xrange(len(scores_list)):
        output.write(str(scores_list[p]) + '\n') # writing to the file
        print repr(str(scores_list[p]))

这样,您就不需要显式地
close()
文件句柄,因为
with
会自动更可靠地处理该句柄。还请注意,您只需将单个参数发送到
range
,它将从0(包括0)迭代到该参数(排除),因此我删除了冗余的起始参数
0
。我还将
range
更改为更高效的
xrange
,因为
range
只有在您希望与Python 3兼容的情况下才会在这里合理地发挥作用,而且您使用的是Python 2风格的
print
语句,因此没有太多意义。

打开文件,清除文件,但是不必要地再次打开同一个文件。当你打开文件时,你会打印一个换行符,即使你不这么认为。下面是令人不快的一句话:

print >> f, ""
在Python2中,它确实做到了这一点

print "" + "\n"
这是因为Python在每个print语句的字符串末尾添加了一个换行符。要停止此操作,可以在语句末尾添加逗号:

print "",
或者直接写:

f.write("my data")
然而,如果您试图保存Python数据类型,并且它不必是人类可读的,那么您可能会幸运地使用它。它的使用非常简单:

def save_score():
    with open('scores.txt', 'w') as f:
        pickle.dump(score_data, f):

这并不是问题的真正答案

这是我的代码版本(未测试)。不要避免重写所有内容;)

函数---
def take_score():
''读取值并转换为int''
分数=[]
以open(“score.txt”、“r”)作为f
对于f中的行:
value=int(line.strip())
分数。附加(值)
返回分数
def保存_分数(分数):
“保存值”
以open(“score.txt”、“w”)作为f
对于分数中的值:
写入(值)
写入(“\n”)
def检查_分数(分数,最小值):
结果=[]
对于分数中的值:
如果值<最小值:
值=最小值
结果。追加(值)
返回结果
#---梅因---
分数=10
分数列表=取分数()
分数列表=检查分数(分数列表,分数)
保存分数(分数列表)

为什么一开始就有一个冗余的
f=open('score.txt','w')
?如果您正在重置函数,为什么不将其截断并打开一次呢?无需清除该文件。当您打开一个文件进行写入时,它将自动清除该文件。所以只要像打开('score.txt',w')一样打开并开始写入它。为什么要创建一个包含readlines的列表,然后将这些行附加到另一个列表中?您可能还希望查找上下文管理器和str.rstrip,并且不必删除换行符来调用intAlso,数据是否必须是人类可读的?你可以使用一种序列化机制,比如
pickle
。在take\u score中,尝试执行
scores\u list。append(line.strip())
不需要
scores\u list[i]。replace(“\n”,”)
,int可以很好地处理换行,索引列表而不是仅仅迭代元素不是很好的。我确信还有改进的余地,但我试图避免完全重写。另外,代码修改了
分数列表
,因此
范围(len)(
至少有一些作用。在“save”函数中这样做可能不太好,但我对程序的了解还不够深入。不过,我会继续删除换行符-这只是不必要的。
# --- functions ---

def take_score():
    '''read values and convert to int'''

    scores = []

    with open("score.txt", "r") as f
        for line in f:
            value = int(line.strip())
            scores.append(value)

    return scores


def save_score(scores):
    '''save values'''

    with open("score.txt", "w") as f
        for value in scores:
            write(value)
            write("\n")


def check_scores(scores, min_value):

    results = []

    for value in scores:
        if value < min_value:
            value = min_value
        results.append(value)

    return resulst

# --- main ---

score = 10

scores_list = take_score()

scores_list = check_scores(scores_list, score)

save_score(scores_list)