初学者分割文本问题


1.txt:

ae!fgmailaefsef
sssss!aef
asas!e23

要求结果(以感叹号分割),并存入2.txt

ae
sssss
asas

代码1,能正确显示在屏幕上:

f = open("1.txt")
for line in f:
    line=line.split('!',1)[0]
    print (line)

代码2:

f = open("\1.txt")
for line in f:
    line=line.split('!',1)[0]
    print (line)
f = open("2.txt",'a')
f.write(line) 
f.close()

结果只有第三行的结果asas,为什么,是因为逐行读取出了问题,还是什么? 如果要输入以某个字符分割,又怎么写?(some_word = input('Input your word: ')?) 谢谢!

  • 4 条回复 | 2 人参与
  • f_r = open("1.txt", "r")
    f_w = open("2.txt", "a")
    for line in f_r.readline():
        f_w.write(line.split("!")[0])
    f_r.close()
    f_w.close()
    
  • @itsneo1990 你好,结果2.txt是aefgmailaefsef,就是第一行字符串去掉感叹号的结果(Python 3.5.3)。

  • @esekata8981 没测就发出来了= =,有两个失误: 1. readlines写成了readline 2. 每行应该附带一个换行符

    所以

    f_r = open("1.txt", "r")
    f_w = open("2.txt", "w")
    for line in f_r.readlines():
        f_w.write(line.split("!")[0])
        f_w.write("\n")
    f_r.close()
    f_w.close()
    
  • @itsneo1990 一直在纠结为什么print (line)和f.write(line) 为什么不一样,原来是换行符的锅。谢谢了。

    cut_word = input('Input your word: ')
    f = open(r"C:\1.txt", "r")
    g = open(r"C:\2.txt", "a")
    with f as f, g as g:
      for line in f:
        line = line.split(cut_word,1)[0]
        print(line)
        g.write(line+"\n")
    
添加一条新回复
登录 或者 注册 后发表回复