【问题标题】:Python file ReadingPython文件读取
【发布时间】:2018-03-04 21:59:36
【问题描述】:

我想从一个文件中批量读取 10 行以下文本。随着行中的每个值到达特定变量,因为我想稍后以连续的方式绘制它们。这是文件数据格式:

Xus level 5 : var1 = 885775, var2 = 50
Xus level 4 : var1 = 885710, var2 = 25
Xus level 3 : var1 = 885705, var2 = 25
Xus level 2 : var1 = 885640, var2 = 100
Xus level 1 : var1 = 885610, var2 = 275
Yus level 1 : var3 = 885510, var4 = 6875
Yus level 2 : var3 = 885505, var4 = 500
Yus level 3 : var3 = 885500, var4 = 225
Yus level 4 : var3 = 885465, var4 = 25
Yus level 5 : var3 = 885460, var4 = 100
... (continue above format with changed values...)

我想在 python 代码中阅读此内容。将值存储在一些变量中,然后一次性绘制 10 行,然后在一些睡眠循环中,我会读取其他 10 行绘制它们,然后重复这些内容直到文件末尾。

【问题讨论】:

  • 如果你想在 python 中做,为什么要用 sed 和 awk 标记它???
  • 你的代码在哪里显示你的努力?

标签: python linux python-2.7


【解决方案1】:

这应该可行。

把你的文件名.txt改成你的文件名

# open your file (Your file name.txt is the file name in read mode (r))
file = open(Your file name.txt", "r")
# for each line in Your File
for line in file:
# Split each word that is inbetween commers into seperate variables
    details =line.split(", ")
    Level1 = details[0]
    Level2 = details[1]

这将保存在 Level1

Yus level{number} : var1 = {number}

在Level2

var2=50

不知道如何摆脱Yus level '1'

而且一次只会做一个,随意修改。

【讨论】:

  • @LeBlue 你的作品比我的好,但不会有 , 在词后[4]
  • 谢谢。如果我想读 10 行,那么当我读完 10 行后,我想读下 10 行。这只是每行的一个循环,我想阅读它,但是一旦我阅读了 10 行,我将进行一些处理,然后我将再次继续相同。明白了吗?
【解决方案2】:

只需按空格分割每一行,然后按索引获取列:

# open file
file = open("filename", "r")

# for each line the file 'filename'
for line in file:

    # split the line in between spaces:
    words = line.split(" ")

    # get the columns by position:
    level = words[2]
    var_name_1 = words[4] 
    var_value_1 = words[6].split(",")[0] # get rid of ,
    # etc

    # do something here ...
    # perhaps add to a list:
    # array_value_1.append(var_value_1)

【讨论】:

  • 谢谢。如果我想读 10 行,那么当我读完 10 行后,我想读下 10 行。这只是每行的一个循环,我想阅读它,但是一旦我阅读了 10 行,我将进行一些处理,然后我将再次继续相同。明白了吗?
猜你喜欢
  • 2011-01-12
  • 1970-01-01
  • 2021-12-22
  • 2014-09-21
  • 2017-09-15
  • 2015-01-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多