Python-将字符串添加到循环中文件的开头

Python-将字符串添加到循环中文件的开头,python,file-io,Python,File Io,我有以下代码: read = open('file.py', 'r+') intent = 0 for line in read: if '{' in line: intent += 1 #print intent, ", up" if '}' in line: #intent -= 1 print intent, ", down" if " " in line: print "ta

我有以下代码:

read = open('file.py', 'r+')

intent = 0

for line in read:
    if '{' in line:
        intent += 1
        #print intent, ", up"
    if '}' in line:
        #intent -= 1
        print intent, ", down"
    if "    " in line:
        print "tab"
我想补充一点

"\t" * intent
从每行开始


如何才能做到这一点?

您可以打开、读取、编辑然后覆盖文件以实现此效果,如下所示:

file=open('file.py', 'r')
lines=file.read().split('\n')
file.close()
output=[('\t'*intent)+i for i in lines]
file=open('file.py', 'w')
file.writelines(output)
file.close()

这就是你想做的吗

read = open('file.py', 'r+')

indent = 0
new_lines = []

for line in read:
    new_lines.append(("\t" * indent) + line)
    if '{' in line:
        indent += 1
    if '}' in line:
        indent -= 1

print("".join(new_lines))

您的问题正文与标题不匹配。这是如何“按索引”写入行的?为什么要以文本形式读取
file.py
文件?@AviBag如果答案解决了您的问题,您可以按上面的绿色勾号。这意味着未来有你问题的人可以更容易地看到答案,并奖励你2rep和回答者15rep。