python - 如何修改文件以使每行的字符数相同?
问题描述
我有一个包含多行数据的文本文件。在将其传递到下游之前,我需要每行具有相同数量的字符。
我有一个 python 脚本,可以找到文件中最长的行,并尝试使用 ljust 函数使每一行都达到该长度。
args=parse_args()
readfile = args.inputfile
#find the longest line in the file, and set that as longest
longest = 0
#open the file up
with open(str(args.inputfile).strip('[]').strip("''")) as readfile:
#find the longest line in the file and make note of how long.
for line in readfile:
if len(line) > longest:
longest = len(line)
else:
pass
print("The longest line is " + str(longest) + " characters long. ")
#make each line exactly that long
for line in readfile:
readfile.write(line.ljust(longest)) #make it longest long and fill with spaces.
readfile.close()
问题是文件没有发生任何事情。该脚本输出最长的行是 31 个字符长,但没有像我期望的那样在较短的行的末尾添加空格。
解决方案
您用尽了文件迭代器;当您尝试写入时,文件中没有任何内容可供访问。如果你费心去追踪执行,你就会看到这一点。请参阅这个可爱的调试博客寻求帮助。
特别是,让我们看看您的循环。
#open the file up
with open(str(args.inputfile).strip('[]').strip("''")) as readfile:
#find the longest line in the file and make note of how long.
for line in readfile:
该for
语句通过file
对象定义的迭代器起作用;您可以将其视为一次性使用主题公园的文件,在您点击with open
声明时设置。
if len(line) > longest:
longest = len(line)
我删除else: pass
了,因为它没有做任何事情。
在这里,离开for
循环时,文件描述符的“书签”位于文件末尾。
print("The longest line is " + str(longest) + " characters long. ")
#make each line exactly that long
for line in readfile:
您不会输入此代码;书签已经在代码的末尾。没有其他东西可以读了。您得到 EOF 响应并完全跳过循环。
readfile.write(line.ljust(longest)) #make it longest long and fill with spaces.
readfile.close()
修复相当简单:仅使用第一个块来确定最大行长度。完全退出该with
块。然后专门为写作制作一个新的。请注意,您需要一个新的输出文件,或者您需要保留第一次读取的输入。您的目的是覆盖原始文件,这意味着您不能同时读取它。
如果这仍然令人困惑,那么请阅读一些关于文件处理的教程。
推荐阅读
- rxjs - 如何在 2 个 observables 发出值并获得发出值的结果后运行代码?
- python - 如何在 BeautifulSoup 中区分带和不带href?
- imagemagick - magick/mogrify -transparent 命令副作用
- amazon-web-services - 达到限制后自动暂停整个 AWS 账户
- python - 如何在一页Django视图上处理两个相同的表单
- app-store - 添加自定义 iOS App Store 开发者图标
- rust - 如何创建两个窗口,第一个显示 OrthographicCameraBundle,第二个显示 UICameraBundle?
- c# - 将文本(字符串值)附加到 txt 文件的每一行
- mongodb - MongoBD Compass querySrv ENODATA _mongodb._tcp.cluster0.yqxra.gcp.mongodb.net
- laravel - 如何在不使用 DB::raw 的情况下编写 Laravel 雄辩的查询,这样它就不必将 MySQL 严格模式设置为 false