我有这个小脚本来排序文本文件的内容
# The built-in function `open` opens a file and returns a file object.
# Read mode opens a file for reading only.
try:
f = open("tracks.txt", "r")
try:
# Read the entire contents of a file at once.
# string = f.read()
# OR read one line at a time.
#line = f.readline()
# OR read all the lines into a list.
lines = f.readlines()
lines.sort()
f.close()
f = open('tracks.txt', 'w')
f.writelines(lines) # Write a sequence of strings to a file
finally:
f.close()
except IOError:
pass
Run Code Online (Sandbox Code Playgroud)
唯一的问题是文本每次被分类时都会显示在文本文件的底部...
我认为它也排除了空白行......任何人都知道为什么?
也许你可以建议一些如何避免这种情况发生的提示?
提前致谢
Joh*_*hin 24
从文本文件读取的"空"行在Python中由仅包含换行符("\n")的字符串表示.您可能还想避免"数据"仅包含空格,制表符等("空白")的行.str.strip()方法允许您检测两种情况(换行符是空格).
f = open("tracks.txt", "r")
# omit empty lines and lines containing only whitespace
lines = [line for line in f if line.strip()]
f.close()
lines.sort()
# now write the output file
Run Code Online (Sandbox Code Playgroud)
小智 6
这是进行基于测试的开发的绝佳机会(见下文).一些观察:
在下面的示例中,我省略了读取和写入文件的方面.在我看来,这对于这个问题并不重要.
我假设您要删除尾随换行符并省略空行.如果没有,你需要调整.(但是你将拥有断言/确认预期行为的框架.)
我同意上面的chryss,你通常不需要在Python中的try块中反复包装东西.我认为,这是来自Java(它强制它)的反模式.
无论如何,这是测试:
import unittest
def sort_lines(text):
"""Return text sorted by line, remove empty lines and strip trailing whitespace."""
lines = text.split('\n')
non_empty = [line.rstrip() for line in lines if line.strip()]
non_empty.sort()
return '\n'.join(non_empty)
class SortTest(unittest.TestCase):
def test(self):
data_to_sort = """z some stuff
c some other stuff
d more stuff after blank lines
b another line
a the last line"""
actual = sort_lines(data_to_sort)
expected = """a the last line
b another line
c some other stuff
d more stuff after blank lines
z some stuff"""
self.assertEquals(actual, expected, "no match!")
unittest.main()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
33056 次 |
| 最近记录: |