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

关于Windows系统下,Python读取文件的问题。

2015-08-10 10:56 621 查看
在windows系统下,Python读取文件需要输入整个路径的名称,可以不是C盘,也可以是中文名字的路径。

 

输入的方法是函数 open(文件地址,’r’)

 

‘r’ 表示读取,’w’ 表示写入,’a’ 表示添加,’+’ 表示读写,’b’ 表示二进制访问

测试代码如下:

a)

filename = raw_input('Enter file name:')

fobj = open (filename, 'r')

for eachLine in fobj:

   print eachLine,

fobj.close()

 

运行后

>>>

Enter file name:G:\interesting\text.txt

I am a learner,

 

I like Python,

 

I want Python read this file.

 

Hello World

 

b) filename = raw_input('Enter file name:')

fobj = open (filename, 'r')

for eachLine in fobj:

   print eachLine,

print 'You makeit! Congratulations!'

 

fobj.close()

 

运行后

Enter file name:G:\interesting\text.txt

I am a learner,

You make it! Congratulations!

 

You make it! Congratulations!

I like Python,

You make it! Congratulations!

 

You make it! Congratulations!

I want Python read this file.

You make it! Congratulations!

 

You make it! Congratulations!

Hello World You make it! Congratulations!

之所以这里会有两行’ You make it! Congratulations!’是因为我在编辑text.txt时候,每一行后面都输入了两个回车

 

c)

filename = raw_input('Enter file name:')

fobj = open (filename, 'r')

for eachLine in fobj:

   print eachLine,

print '\n\

\

You make it! Congratulations!'

 

fobj.close()

运行后

>>>

Enter file name:G:\interesting\text.txt

I am a learner,

 

I like Python,

 

I want Python read this file.

 

Hello World

You make it! Congratulations!

在这里,我们发现,在print函数当中,’\n’会打印一个回车,’\’表示换行后继续打印,但是不管换几行,都会直接跳过这些回车,而不是打印这些回车。

 

d)更改文件名为’测试.txt’

filename = raw_input('Enter file name:')

fobj = open (filename, 'r')

for eachLine in fobj:

   print eachLine,

print '\n\

\

You make it! Congratulations!'

 

fobj.close()

 

运行后

>>>

Enter file name:G:\interesting\测试.txt

I am a learner,

 

I like Python,

 

I want Python read this file.

 

Hello World

You make it! Congratulations!

 

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