作者bob123 ()
看板Python
标题Re: [问题] 档案空白删除
时间Sat May 5 09:17:42 2012
同时读写用'r+'
with open("a.txt","r+") as f:
pos_read, pos_writen = 0, 0
line = None
while '' != line:
line = f.readline()
if '' == line.strip():continue
pos_read = f.tell()
# overwrite
f.seek(pos_writen,0)
f.write(line)
pos_writen = f.tell()
# put pointer back for reading
f.seek(pos_read)
# drop everything else
f.truncate(pos_writen)
不过小弟这边处理的文字档通常大不到哪里
所以会用这种相较起来好懂的写法
content = []
with open("a.txt","r") as fin:
content = [line for line in fin if ''!=line.strip()]
with open("a.txt","w") as fout:
fout.writelines(content)
※ 引述《shihyuyao (shihyuyao)》之铭言:
: ※ 引述《Jason1122 (Jason1122)》之铭言:
: : w再开一个档案来存:
: : with open("t.txt", "r") as f:
: : with open("t2.txt", "w") as o:
: : for line in f:
: : if line != "\n":
: : o.write(line)
: : t2改成t会变空白,同个档案可能要别的方法吧
: : 1.txt
: : AAA
: : BBB
: : CCC
: : 2.txt 拿掉空白变成
: : AAA
: : BBB
: : CCC
: : 我想把1.txt 每列的空白删除,有办法在同一个档案做完吗?
: : 还是要再开另一个档案2.txt才可以?
: : 读出的每一列怎麽判断是不是空白?
: : infile = open(1.txt, 'r');
: : outfile = open(2.txt, 'w');
: : for line in infile:
: : //这边要怎麽判断空白跳过在档案输出到2.txt?
: : 谢谢
: +++++++++++++++++++++++++++++++++++++++++++
: if line != "\n":
: 这样是比对字串最後一个字元吗?
: AAA後面还有一个"\n"??
帮回
这是比整行
AAA\n != \n 写入
\n == \n 不理
\n == \n 不理
BBB\n != \n 写入
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 111.255.10.61