Как создать файл без расширения pycharm

Обновлено: 07.07.2024

у меня есть ошибка ввода в pycharm при отладке и запуске.

моя структура проекта укоренена должным образом, etc./HW3/. , Так что HW3 является корневым каталогом.

у меня есть подпапка в HW3, util , а также файл util/util.py . У меня есть еще один файл в util под названием run_tests.py .

на run_tests.py , у меня есть следующая структура импорта,

это дает ошибку ввода, from util.util import load_dataset,proportionate_sample ImportError: No module named 'util.util'; 'util' is not a package

однако, в точно такой же проект, в другом каталоге (тот же уровень, что и util ) позвонил data , у меня есть файл data/data_prep.py , которая также импортирует функции из util/util.py использование аналогичного оператора импорта. и он работает без каких-либо проблем.

очевидно, я делаю это как домашнее задание, поэтому у меня нет такого опыта. но я сделал эту точную конфигурацию для последних 3 homeworks и столкнулся с нулевыми проблемами, поэтому я понятия не имею, как даже устранить эту проблему,особенно когда другой файл работает.

проблема исчезает, когда я перемещаю файл в другой каталог. Поэтому я думаю, что этот вопрос как импортировать файл python, расположенный в том же каталоге в проекте pycharm? потому что pycharm вызывает ошибку, если я делаю import util и предлагает мне использовать полное имя из корня.

если у вас нет __init__.py создайте один и добавьте эту строку

затем вы можете легко импортировать модуль в ваших скриптах the __init__.py говорит python, что он должен рассматривать эту папку как пакет python, его также можно использовать для импорта/загрузки модулей.

в большинстве случаев __init__.py пусто.

со ссылкой на документы

The __init__.py файлы необходимы, чтобы заставить Python лечить каталоги, содержащие пакеты; это делается для предотвращения каталоги с общим именем, например string, из непреднамеренно скрытие допустимых модулей, которые возникают позже в пути поиска модуля. В самый простой случай, __init__.py может быть просто пустой файл, но это может быть также выполните код инициализации для пакета или установите __all__ переменная, описанная позже.

Рекомендуется:

убедитесь, что рабочая папка установлена как Sources .

вы можете сделать это Pycharm -> Preferences -> Project: XYZ -> Project Structure

выберите рабочую папку и отметьте ее как Sources . Затем Pycharm распознает рабочую папку как исходную папку для проекта, и вы сможете просто добавить другие файлы в эту папку, используя

не рекомендуется:

на Pycharm вы можете просто добавить . до .py файл, который вы собираетесь импортировать из папку. В вашем случае это будет

Примечание: может быть немного не связаны.

For language-specific features (such as syntax highlighting and code analysis ) in files representing different languages and technologies, PyCharm maintains a list of file types , each of which links a language service with one or more filename patterns.

The default list of file types covers all relevant filename patterns, but you can add new file types for your custom language files and change the associated filename patterns for existing file types.

If you are working on a language that is not supported in PyCharm by default, there might be plugins supporting that language depending on the PyCharm edition.

When you open a file in the editor, PyCharm chooses the file type and the corresponding language service according to the filename pattern. If the filename doesn't match any of the patterns registered for file types, PyCharm helps to associate the filename pattern with a specific file type.

Apart from that, you can make PyCharm the default application for opening specific file types from the file manager on your operating system.

Add a custom file type

If you work on a language that is not supported by default and there are no plugins for it, you can configure a simple language service for files associated with this language — you will enjoy syntax highlighting for keywords, comments, and braces and have some basic editor helpers such as adding line/block comments with Ctrl+/ / Ctrl+Shift+/ and extending/shrinking selection according to the structure with Ctrl+W / Ctrl+Shift+W .

Press Ctrl+Alt+S to open the IDE settings and select Editor | File Types .

In the Recognized File Types section, click , specify the name of the new type, and provide a description.

In the Syntax Highlighting section, configure case sensitivity, brace matching settings, and specify ways of defining comments:

Line comment : specify characters that indicate the beginning of a single-line comment.

Only at line start : characters that indicate the beginning of a line comment are recognized as a comment if they are located in the beginning of a line.

Block comment start , Block comment end : specify characters that indicate the beginning and the end of a block comment.

Hex prefix : specify characters that indicate that the subsequent value is a hexadecimal number (for example, 0x ).

Number postfixes : specify characters that indicate which numeric system or unit is used. A postfix is a trailing string of characters (for example, e-3, kg ).

Support paired braces , Support paired brackets , Support paired parens , Support string escapes : select these checkboxes to highlight paired braces, brackets, parentheses, and string escapes.

In the Keywords section, you can specify up to four lists of keywords. Keywords of each list will be highlighted differently in the editor and will be auto-completed.

The Ignore case checkbox indicates whether keywords in files of the custom format are case-sensitive.

You can customize colors for syntax highlighting of language-specific keywords, comments, and other identifiers on the Editor | Color Scheme | User-Defined File Types settings page.

Configure associations between filename patterns and file types

Associate a filename pattern with specific file type

If PyCharm cannot identify the type of the file that you are trying to open or create, it displays the Register New File Type Association dialog where you can choose the way you want to process this file.

If the dialog doesn't appear automatically, right-click the file in the Project tool window and select Associate with File Type from the context menu or choose File | File Properties | Associate with File Type from the main menu.

In the Register New File Type Association dialog, select the necessary options:

From the File pattern list, select whether you want to specify a type for the current file ( file.extension ) or for all files with this extension ( *.extension ).

Select one of the following options:

Open matching files as text and auto-detect file type by content : open the file without an extension as a text file and identify its type by the content, for example, by the shebang line.

Open matching files in PyCharm : associate the file with one of the existing file types. You can change this association later in the settings.

Open matching files in associated application : open the file in the default system application configured in your operating system. For example, .pdf files are opened in the default PDF viewer.

If necessary, you can check and configure all filename patterns associated with system applications.

Click OK to apply the settings.

Change filename patterns associated with file type

Press Ctrl+Alt+S to open the IDE settings and select Editor | File Types .

From the Recognized File Types list, select the file type that you want to associate with other filename patterns.

Use the File name patterns section to make the necessary changes. You can add a new pattern (), remove an existing one (), or modify an existing pattern ( ).

If your project contains files in proprietary formats, such as .pdf and .docx , PyCharm will open these files using the default application configured in your operating system. When a specific proprietary file format is not recognized or you just want to open certain files with the system application, you can add the necessary associations.

Configure filename patterns associated with system applications

Press Ctrl+Alt+S to open the IDE settings and select Editor | File Types .

In the Recognized File Types list, select Files opened in associated applications .

In the File name patterns section on the right, click and specify a filename pattern that should be associated with an external application.

If a file is correctly associated with a specific file type by its filename pattern, but you want to process this file differently, you can override the file type association for this file only — other files matching that pattern will not be affected.

Override file type for specific file

In the Project tool window ( Alt+1 ), select one or more files that should have another file type association

, right-click the selection and choose Override File Type .

From the list that opens, select a new file type.

Use speed search to find the required file type faster.

Make PyCharm the default app for specific file types

You can make PyCharm the default application for opening specific file types from the default file manager on your operating system.

Press Ctrl+Alt+S to open the IDE settings and select Editor | File Types .

Click Associate File Types with PyCharm and select the file extensions you want to open with the IDE.

Click OK and close the dialog.

If you're using macOS, restart your computer to apply the changes.

Ignore files and folders

PyCharm also maintains a list of files and folders that are completely excluded from any kind of processing. Out of the box, this list includes temporary files, service files related to version control systems, and so on:

Modify the list of ignored files and folders

Press Ctrl+Alt+S to open the IDE settings and select Editor | File Types .

Switch to the Ignored Files and Folders tab.

You can add a new extension (), remove an existing one (), or modify an existing extension ( ).

Apply the changes and close the dialog.

Configure shebang commands for file types

Press Ctrl+Alt+S to open the IDE settings and select Editor | File Types .

From the Recognized File Types list, select the file type for which you want to configure a command.

In the HashBang patterns area, click ( Add HashBang Pattern) .

In the dialog that opens, specify the pattern that the IDE will use to recognize a file type, then click OK .

PyCharm brings powerful support for HTML that includes syntax and error highlighting, formatting according to the code style, structure validation, code completion, on-the-fly preview during a debugging session (Live Edit) or in the dedicated preview tab in the code editor, and much more.

HTML specification is configurable with the Default HTML language level preference on the Languages and Frameworks | Schemas and DTDs page of the IDE settings Ctrl+Alt+S . By default, specification HTML 5.0 from W3C is assumed.

Create an HTML file

From the main menu, select File | New , and then select HTML File from the list. PyCharm creates a stub file based on the HTML file template and opens it in the editor.

Create references in an HTML file

Inside a <script> , <link> , or <img> tag, PyCharm suggests completion for the path to the file you are referencing.

Alternatively, in the Project tool window, select the JavaScript, CSS, or image file you want to reference and drag it into the HTML file. PyCharm generates the <script> , <link> , or <img> tags inside <head> . For <img> tags, PyCharm also generates the width and height attributes.

Wrap code fragments in tags

Select the code fragment to wrap and press Ctrl+Alt+T or select Code | Surround With from the main menu.

From the list, select Wrap with Tag . PyCharm encloses the selection in a pair of brackets ( <> and </> ).

Type the tag inside the opening brackets <> . PyCharm automatically fills in the tag in the closing brackets </> .

Documentation look-up

For most HTML tags and attributes PyCharm can show you a summary from the corresponding MDN article. This summary is displayed in the Documentation popup which also shows the deprecation status of a tag or an attribute and information on its compatibility with various browsers.

If the tag or the attribute is available in all versions of browsers, PyCharm does not show any information about its compatibility.

HTML quick documentation: attribute is available in all versions of browsers

Otherwise, the Documentation popup also lists the browsers and their versions that support the tag or the attribute.

HTML quick documentation: compatible browsers are listed

Compatibility is checked only for Chrome, Chrome Android, Safari, Safari iOS, Firefox, Internet Explorer, and Edge.

If the tag or the attribute is deprecated, the popup also informs you about this status.

HTML quick documentation: status Deprecated for <big> tag

View documentation for a tag or an attribute

Position the caret at the tag or the attribute and press Ctrl+Q or select View | Quick Documentation Lookup from the main menu.

When you hover the mouse pointer over a tag or an attribute, PyCharm immediately displays the reference for it in the Documentation popup.

You can turn off this behavior or configure the popup to appear faster or slower, see Configuring the behavior of Documentation popup below.

Configure the behavior of Documentation popup

To turn off showing documentation automatically, open the Settings/Preferences dialog Ctrl+Alt+S , go to Editor | Code Editing , and clear the Show quick documentation on hover checkbox.

To have the Documentation popup shown faster or slower, open the Settings/Preferences dialog Ctrl+Alt+S , go to Editor | General | Code Completion , then select the Show the documentation popup checkbox and specify the delay time.

Open the MDN documentation for tags and attributes in the browser

In the Documentation popup Ctrl+Q , click the link at the bottom.

Press Shift+F1 or select View | External Documentation from the main menu.

Preview output of HTML files

You can open the output of your HTML code in the built-in PyCharm preview or externally, in a browser of your choice.

By default the built-in server port is set to the default PyCharm port 63342 through which PyCharm accepts connections from services. To change this default value, open the Settings/Preferences dialog Ctrl+Alt+S , go to Build, Execution, Deployment | Debugger , and in the Built-in Server specify any other value starting from 1024.

By default, after you open an HTML file in the browser or in the built-in preview, PyCharm automatically reloads the page every time this HTML file (or any linked JavaScript or Style Sheet file) is saved manually or automatically, see Save and revert changes.

You can change the default behavior to reload the page as you type so the changes to the HTML or related file immediately appear in the browser or in the built-in preview. See Configure automatic reload below.

PyCharm built-in preview

PyCharm built-in preview makes your work faster as you no longer need to switch to the browser and refresh the pages. The preview is opened in a separate editor tab and reloaded automatically as you type or when you save the changes, depending on the reload behavior.

Open the PyCharm built-in preview

From the main menu, select View | Open in Browser , and then select Built-in Preview from the list.

Alternatively, hover your mouse pointer over the code to show the browser icons popup, and click .

Preview an HTML file in a browser

To make sure your HTML code is rendered properly in production environment, preview HTML files in specific browsers. The page is reloaded automatically when you save the changes or as you type, depending on the reload behavior.

From the main menu, select View | Open in Browser , and then select the desired browser from the list.

To open the default PyCharm browser, select Default .

Alternatively, hover your mouse pointer over the code to show the browser icons popup, and click the icon that indicates the desired browser:

If you have only one browser configured, just press Alt+F2 .

Configure the browser icons in the popup

Open the Settings/Preferences dialog Ctrl+Alt+S and go to Tools | Web Browsers .

To hide some of the icons, clear the Active checkboxes for the unnecessary browsers.

To hide the whole popup, clear the For HTML files checkbox.

Configure automatic reload

By default, after you open an HTML file in the browser or in the built-in preview, PyCharm automatically reloads the page every time this HTML file (or any linked JavaScript or Style Sheet file) is saved manually or automatically, see Save and revert changes.

When you save a file that triggers page reload, PyCharm shows a Got it tooltip.

Reload on save: Got it tooltip

You can change the default behavior to reload the page as you type so the changes to the HTML or related file immediately appear in the browser or in the built-in preview.

Go to the Tools | Web Browsers and Preview page of the IDE settings Ctrl+Alt+S . Alternatively, click Configure in the Got it tooltip.

In the Reload behavior area, from the Reload page in browser and Reload page in built-in preview lists, select the actions that will trigger automatic reload of pages in web browsers and in the built-in preview. By default, On Save is selected.

Select On Change to reload pages as you update the corresponding HTML file or linked files.

Select Disabled to suppress automatic upload.

The changes to the reload behavior only take effect after you close the currently opened built-in or browser preview.

View HTML source code of a web page in the editor

Press Ctrl+Shift+A and select Open Source Code from URL. from the list.

In the Open URL dialog that opens, type the URL address of the web page or choose a previously opened URL from the list.

View embedded images

PyCharm offers several ways to view images embedded in an HTML file. You can use navigation to source, open an image in an external graphical editor, or preview images on-the-fly.

View images in PyCharm

Select the image file in the Project tool window and press F4 .

Alternatively, position the caret at the reference to the image in the editor and press Ctrl+B

To preview an image in a popup instead of in a separate tab, select the reference to it and press Ctrl+Shift+I

View images in an external editor

Select the image file in the Project tool window, and select Jump to external editor or press Ctrl+Alt+F4 .

PyCharm opens the image in the editor that is used in your OS by default. You can configure another image editor in which the IDE will open files.

Change the default external editor

Right-click an image in the editor and select Edit Path to External Editor from the context menu.

You can also press Ctrl+Shift+A and type Edit Path to External Editor .

In the Path to External Editor dialog, specify the path to the application in which you want to open images and click Save .

Extract include files

You can extract a fragment of HTML code into a separate include file. Entire JavaScript code blocks inside a <script> tags can be extracted as well. PyCharm also suggests adding references instead of duplicates of the selected fragment.

In the editor, select the code block to be extracted and choose Refactor | Extract | Extract Include File from the main menu or from the context menu of the selection.

In the Extract Include File dialog that opens, specify the name of the include file without the extension and the directory to store it in. You can accept the predefined directory or select another one.

Click OK , when ready. PyCharm extracts the selected source code into the specified file in the target directory and generates the corresponding reference in the source file.

Configure syntax highlighting

You can configure HTML-aware syntax highlighting according to your preferences and habits.

In the Settings/Preferences dialog Ctrl+Alt+S , go to Editor | Color Scheme | HTML .

Select the color scheme, accept the highlighting settings inherited from the defaults or customize them as described in Colors and fonts.

Никита Машков

Никита Машков запись закреплена

Как в пайчарме создать css файл, чтобы он не был как текстовой

Евгений Кунгуров

Никита Машков


Никита Машков

Евгений, я создаю сначала текстовой файл потом, меняю расширение на css

Евгений Кунгуров

Никита Машков


Никита Машков ответил Евгению

Евгений Кунгуров

Василий Черепанов


Василий Черепанов ответил Никите

Никита, ты хочешь сказать, что у тебя нет подсветки CSS файлов? Если да, то это нормально, когда ты используешь community версию пайчарма.

Александр Ушаков

Vasily, Не сталкивались случаем когда в static django - css файл не меняет фон даже после обновления кэша в браузере?

Василий Черепанов


Василий Черепанов ответил Александру

Читайте также: