假设我有一个格式如下的文本文件:
100 20只鸟在飞翔
我想将int(s)读入自己的列表,将字符串读入自己的列表……我将如何在python中进行此操作.我试过了
data.append(map(int, line.split()))
那没用……有什么帮助吗?
解决方法:
基本上,我正在逐行读取文件,并将它们分开.我首先检查是否可以将它们转换为整数,如果我失败了,将它们视为字符串.
def separate(filename):
all_integers = []
all_strings = []
with open(filename) as myfile:
for line in myfile:
for item in line.split(' '):
try:
# Try converting the item to an integer
value = int(item, 10)
all_integers.append(value)
except ValueError:
# if it fails, it's a string.
all_strings.append(item)
return all_integers, all_strings
然后,给定文件(‘mytext.txt’)
100 20 the birds are flying
200 3 banana
hello 4
…在命令行上执行以下操作返回…
>>> myints, mystrings = separate(r'myfile.txt')
>>> print myints
[100, 20, 200, 3, 4]
>>> print mystrings
['the', 'birds', 'are', 'flying', 'banana', 'hello']
标签:python,file-io
来源: https://codeday.me/bug/20190723/1514017.html