create file object in python 3.7 - python-3.x

I have python 2.7 code with creates a builtin file object which return me a file object <type 'file'>
file(os.path.join('/tmp/test/', 'config.ini'))
Same code i changed in python 3.7 as below it returns <class '_io.TextIOWrapper'>
open(os.path.join('/tmp/test/', 'config.ini'))
How can i get a file object type in python 3

You can use them the exact same way.
file = open(os.path.join("/tmp/test/", "config.ini"))
print(file.read()) # Will print file contents
Or use pathlib:
from pathlib import Path
file = Path("/tmp/test") / "config.ini"
print(file.read_text()) # will do the same
You're not looking for a file object. You're looking for an object that'll let you read and write files.

Related

Using .stem with full path to file in Python 3

How can I get the full path to a file without the file extension using .stem?
I have tried:
from pathlib import Path
for i,file in enumerate(os.listdir(os.environ['onedrive'])):
if file.endswith(".txt"):
print("Full file path without extension using stem:", os.path.realpath(file).stem)
Error:
AttributeError: 'str' object has no attribute 'stem'
perhaps I am calling the path to the file incorrectly, but I am not sure how else.

How do I open a csv file using VS python Jupiter cells

I have been trying to set The Desktop as my working Directory, so I can load a csv
import os
path="/Users/HOME/Desktop"
os.getcwd()
It returns
/
using pandas library I'm failing to use
DF = pd.read_csv("filename", "mode")
You did not actually change the working directory, you merely assigned a path to a variable. You need to invoke os.chdir() with that path (see https://stackoverflow.com/a/431715/14015737):
import os
path="/Users/HOME/Desktop"
os.chdir(path)
os.getcwd()
This should return the path.
In order to then read your .csv file that is located there (e.g. /Users/HOME/Desktop/test.csv) you can call read_csv() without a path. Full example:
import os
import pandas
path='/Users/HOME/Desktop'
os.chdir(path)
df = pandas.read_csv('test.csv')

How to get absolute pyc file path with python 3.x?

How can we get the compiled python pyc file path with python 3.x in the current environment? I know it's in the __pycache__ direcotry, but I couldn't find a way to find the file path. Because the names of pyc files of python 3 changes by the environment.
Given that you know the path to the source (ie .py) file, there's a function importlib.util.cache_from_source that does exactly what you want. For example, to get the .pyc file corresponding to the numpy package, you would do:
import importlib
import numpy
importlib.util.cache_from_source(numpy.__file__)
For me (on OS X), this prints out something along the lines of:
/<absolute path to site-packages>/numpy/__pycache__/__init__.cpython-36.pyc

Read csv file Anaconda | Python 3

I am trying to open a CSV file on Anaconda (Python 3) unsuccessfully.
I tried with a raw string, I included the whole path and also tried with the double backslashes but nothing worked. I still get the Errno 2 No such file or directory.
This is my code:
reader = csv.reader(open(r'C:\Users\Marco\Desktop\trainingset.csv', newline=''), delimiter=' ', quotechar='|')
for row in reader:
print(", ",join(row))
I have the same issue when trying to open a csv file this way... I don't know the reason but instead, I use the pandas library that has a method named read_csv()
pandas.read_csv('myfile.csv')
It gets the content of your csv file as a dataframe object. This works with Python 3.5 using Anaconda3.

python 3 and the file object

I am looking at using setup.py to automatically generate python 3 code from python 2 sources using the 'use_2to3' attribute. My setup.py script includes the following statement:
VERSION = None
with file('version','rt') as FF:
VERSION = FF.read().lstrip().rstrip()
print("VERSION %s" % (VERSION) )
When I type 'python3 setup.py build' I get the error:
Traceback (most recent call last):
File "setup.py", line 18, in <module>
with file('version','rt') as FF:
NameError: name 'file' is not defined
which I understand is correct as the file object no longer exists and I should change it to 'open()'.
The concern is that the '2to3' utility does not detect this and leaves the code untouched.
I unfortunately use this idiom throughout my code.
Is this a bug in '2to3' ?
Use the open instead of the file.
It was tempting to use the file() instead of the open() in Python 2.x -- especially for those with OO background. The file() call resembled calling a constructor for creation of a file object. However, it was always recommended to use open() function instead. This may be the reason why 2to3 does not solve the case.
In Python 3, the file is unknown. The file objects are of the _io.TextIOWrapper class:
>>> f = open('a.txt', 'w')
>>> type(f)
<class '_io.TextIOWrapper'>
>>> f.__class__.__name__
'TextIOWrapper'

Resources