【问题标题】:how can i ignore a line which contains alphanumeric character while reading a text file in python在python中读取文本文件时如何忽略包含字母数字字符的行
【发布时间】:2020-01-23 17:52:20
【问题描述】:

我正在阅读 python 中的文本文件,其中主要包含数字行以及一些字母数字行。我需要分离奇数和偶数并写入新文件,但是当它进入字母数字行时出现错误。请帮忙。 例如....说txt文件包含以下....2,4,6,10p等。我尝试使用此代码。在将偶数和奇数写入相应的文件之后,我希望这段代码能够正常工作....应该说,您的工作已经完成,但这些行保持原样....我们可以这样做吗??

file = open("num.txt","rt")
even = open("even.txt","w+")
odd = open("odd.txt","w+")
for i in file:
    if i.strip:
        num = int(i)
        if (num % 2 == 0):
            even.write(str(num))
            even.write("\n")

        else:
            odd.write(str(num))
            odd.write("\n")

但它显示以下错误

File "G:/Py_projects/odd_even.py", line 6, in <module>
    num = int(i)
ValueError: invalid literal for int() with base 10: '10p\n'

进程以退出代码 1 结束 请回复。谢谢。

【问题讨论】:

  • 欢迎来到 StackOverflow。见minimal, reproducible example。在您发布 MRE 代码并准确说明问题之前,我们无法有效地帮助您。我们应该能够将您发布的代码粘贴到文本文件中并重现您指定的问题。
  • On topichow to ask 和 ...the perfect question 在这里申请。 StackOverflow 是一个针对特定编程问题的知识库。
  • 可以使用字符串.isdigit()函数判断字符串是否只包含数字。
  • isalnum() 是您正在寻找的。​​span>
  • 如果一行是2,4,6,10p,您是要跳过整行还是处理其中的数字?

标签: python list file file-io


【解决方案1】:

假设您的文本文件如下所示。

test.txt
1
2
3 
4
5
6
10p
4
83
456
497987
4564
6589
5493
321654

这应该适合你。

with open('test.txt','r') as f:
    even=[]
    odd=[]
    alphanum=[]
    for line in f:
        val=line.strip('\n').strip()
        if val.isdigit():
            if int(val)%2==0:
                even.append(int(val))
            else:
                odd.append(int(val))
        else:
            alphanum.append(val)
with open('even.txt','w') as f1:
    for i in even:
        f1.write(str(i)+'\n') #writing even numbers to even.txt file

print(even)
print(odd)
print(alphanum)

按照 cmets 中的建议 AMCval=line.strip('\n').strip() 重写为 val=line.strip('\n ')


您必须对oddalphanum 执行相同的操作。

输出

[2, 4, 6, 4, 456, 4564, 321654]
[1, 3, 5, 83, 497987, 6589, 5493]
['10p']

【讨论】:

  • @ASHISHPRIYADERSHY 如果回答对您有帮助。请通过单击答案旁边的勾号来接受此答案。它有助于整个社区确定正确的答案。干杯。
  • 不能把.strip('\n').strip()写成.strip(\n )吗?
  • @AMC 是的,你是对的。编辑答案并添加学分。感谢您花时间改进答案。
【解决方案2】:
with open('file.txt','r') as f:
    for line in f:
        line = line.strip('\n').strip()
        if line.isdigit():
            if int(line) % 2 == 0:
                with open  ('even.txt', 'w') as e:
                     e.write (line + '\n')
            else:
                with open ('odd.txt', 'w') as o:
                     o.write (line + '\n')
        elif line.isalnum():
            with open ('alphanum.txt', 'w') as a:
                     a.write (line + '\n')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-27
    • 2015-03-31
    • 2012-01-18
    • 2018-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多