简体   繁体   English

如何删除文件中每行的最后3个字符?

[英]How to delete the last 3 characters from every line in a file?

Can anyone give me some advice on creating a loop to cut the last 3 characters from every line within a input file? 谁能给我一些建议,以创建一个循环来剪切输入文件中每行的最后3个字符?

I have tried 我努力了

iFile = iFile[:-3]

and

iFile = iFile.replace(':', '')[:-3]

but neither seem to work as I'm getting a: 但似乎都无法正常工作,因为我得到了:

TypeError: 'file' object has no attribute '__getitem__'

First open the file and then you will have to loop over the lines as follows 首先打开文件,然后您必须如下遍历行

myfile = open(fileName)
for j in myfile:
    print j[:-3]

That all! 就这些!

Replace 更换

iFile = iFile[:-3]

with

line = line[:-3]

You can also use regular expression string substitution. 您也可以使用正则表达式字符串替换。 This helps to prevent IndexError if you have lines that are shorter than three characters: 如果您的行少于三个字符,这有助于防止IndexError

import re
with open(fileName, 'r') as myfile:
    for line in myfile:
        print re.sub('.{0,3}\Z', '', line)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM