您的位置:首页 > 编程语言 > Python开发

python按行读取文件 去掉换行符"\n"

2013-12-27 12:16 453 查看
转自:/article/7987253.html

eg:

[python] view
plaincopy

#! /usr/bin/python

import sys

import string

import os

base_dir="/home/qinjianwang/mtr_dir/2012_09_12/tw"

as_uniq_info=base_dir + "/as_uniq_info"

get_line_num="wc -l " + as_uniq_info + " | awk '{print $1}'" ###get the lines of "as_uniq_info"

line_num = os.popen(get_line_num).read().strip('\n')

global VEXNUM

[python] view
plaincopy

VEXNUM = string.atoi(line_num)

python 字符串连接

[python] view
plaincopy

base_dir="/home/qinjianwang/mtr_dir/2012_09_12/tw"

as_uniq_info=base_dir + "/as_uniq_info"

有:as_uniq_info="/home/qinjianwang/mtr_dir/2012_09_12/tw/as_uniq_info"

需要注意以下这句:

[python] view
plaincopy

get_line_num="wc -l " + as_uniq_info + " | awk '{print $1}'" ###get the lines of "as_uniq_info"

注意1:拼接shell命令时,需要引用python中的变量as_uniq_info,as_uniq_info单独拿出来,再拼接其它命令,不要写成下面这样:

[python] view
plaincopy

get_line_num="wc -l as_uniq_info | awk '{print $1}'"

这样写会造成shell无法正确替换python中的变量as_uniq_info。

注意2:拼接shell命令时,要注意引号中命令间的留空,如以下

[python] view
plaincopy

"wc -l " 和 " | awk '{print $1}'"

引号"wc -l “中的 -l 后面就需要留空,要注意。

python 调用 shell

get_line_num="wc -l as_uniq_info | awk '{print $1}'" ###get the lines of "as_uniq_info"

line_num = os.popen(get_line_num).read().strip('\n')

get_line_num 作为shell执行的命令,会取得文件as_uniq_info文件的行数

os.popen(get_line_num):执行shell

get_line_num = os.popen(get_line_num).read():调用read,赋值给get_line_num,此时get_line_num中含有一个换行符("\n")。

os.popen(get_line_num).read().strip('\n'):去掉换行符

shell 引用python变量

[python] view
plaincopy

line_num = os.popen(get_line_num)

引用了python中的get_line_num变量。

python引用shell中值

[python] view
plaincopy

line_num = os.popen(get_line_num).read()

执行完shell后,通过read()函数,赋值给python中的变量line_num

python 去掉换行符"\n"

[python] view
plaincopy

line_num = os.popen(get_line_num).read().strip('\n')

通过strip()函数,去掉换行符"\n"

python按行读取文件 去掉换行符"\n"

[python] view
plaincopy

for line in file.readlines():

line=line.strip('\n')

Python 字符转实型

[python] view
plaincopy

b="123.678"

>>> string.atof(b)

123.678

Python 字符转整型

[python] view
plaincopy

VEXNUM = string.at
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: