简体   繁体   English

Python读取文件中的每个字符串

[英]Python Reading Each String in a file

I have a text file: 我有一个文本文件:

1 0 1 0 1 0

1 0 1 0 1 0

1 0 1 0 1 0

1 0 1 0 1 0

I want to be able to retrieve each string and convert it to an integer data type but my piece of code results in ValueError: invalid literal for int() with base 10: '' 我希望能够检索每个字符串并将其转换为整数数据类型,但是我的代码片段导致ValueError: invalid literal for int() with base 10: ''

tile_map = open('background_tiles.txt','r');

    for line in tile_map:

        for string in line:

             self.type = int(string);

What is the correct way to retrieve the data and convert it successfully? 检索数据并成功转换的正确方法是什么?

One thing to remember when iterating through the file is that the newline character is included, and when you try to cast that using int() , you will receive the error you are referencing (because Python doesn't know how to convert it into an integer). 遍历文件时要记住的一件事是包括换行符,并且当您尝试使用int() ,您将收到所引用的错误(因为Python不知道如何将其转换为整数)。 Try using something like: 尝试使用类似:

with open('background_tiles.txt', 'r') as f:
    contents = f.readlines()

for line in contents:
    for c in line.split():
        self.type = int(c)

The with is a context manager, and it is generally a more efficient way to deal with files as it handles things like closing for you automatically when it leaves the block. with是一个上下文管理器,通常是一种处理文件的更有效的方式,因为它可以处理诸如离开该块时自动为您关闭等操作。 readlines will read the file into a list (each line represented as a list element), and split() splits on the space. readlines将文件读入一个列表(每行表示为一个list元素),然后split()在该空格上拆分。

Your line contains string like - "1 0 1 0 1 0" . 您的行包含类似于- "1 0 1 0 1 0"字符串。 You need to split your line on space: - 您需要在空间上分割线:-

for string in line.split():
    self.type = int(string);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM