[Tutor] new to python
Peter Otten
__peter__ at web.de
Sun Jul 23 04:23:36 EDT 2017
N6Ghost wrote:
> C:\coderoot\python3\level1>python
> Python 3.6.2 (v3.6.2:5fd33b5, Jul 8 2017, 04:14:34) [MSC v.1900 32 bit
> (Intel)] on win32
> Type "help", "copyright", "credits" or "license" for more information.
>
> /windows 10 x64
>
> new to python, but not really new to programming.
>
> going through the beginners docs, I am stuck on the file handling opening:
>
>
> my code so far:
>
> f = open("C:\coderoot\python3\level1\inputfile.txt", 'r')
While this one is OK using backslashes in a normal string will sooner or
later produce erroneous paths:
>>> print("C:\test")
C: est
Oops, \t is a TAB char, not a backslash followed by a 't'. Possible
solutions are
- always escape the backslash "C:\\test"
- use raw strings r"C:\test"
- use forward slashes for file paths: "C:/test" (yes, it works even on
windows)
> for line in file:
It looks like file isn't defined anywhere.
> for line in f:
> print(line.rstripe())
> f.close()
It looks like f.close() is indentend one level to deep -- the file will be
closed on the second iteration of the inner loop.
Indentation is important as Python uses it to represent the code structure.
If your editor alows it ensure that it converts one hit of the TAB key into
four spaces to avoid discrepancies between what you see and what you have.
> I want to try the different methods of opening files and reading them.
> and processing the data. from there I will then start with writing to
> files.
>
>
> any idea why that does not work?
Since you can already program:
Read the traceback and error message carefully -- they prodvide valuable
hints.
If you cannot make sense of them please provide them along with the code
that produced them; use cut-and-paste for both code and traceback.
More information about the Tutor
mailing list